我正在尝试在我的Xamarin Forms项目(PCL)中实现自定义渲染器。我试图弯曲标签的角落。 问题是它不能渲染。我在相关文件中抛出一个调试,但它们正在被击中,但它们似乎没有渲染。
以下是标签的子类:
public class CurvedCornersLabel:Label
{
public static readonly BindableProperty CurvedCornerRadiusProperty =
BindableProperty.Create(
nameof(CurvedCornerRadius),
typeof(double),
typeof(CurvedCornersLabel),
12.0);
public double CurvedCornerRadius
{
get { return (double)GetValue(CurvedCornerRadiusProperty); }
set { SetValue(CurvedCornerRadiusProperty, value); }
}
public static readonly BindableProperty CurvedBackgroundColorProperty =
BindableProperty.Create(
nameof(CurvedCornerRadius),
typeof(Color),
typeof(CurvedCornersLabel),
Color.Default);
public Color CurvedBackgroundColor
{
get { return (Color)GetValue(CurvedBackgroundColorProperty); }
set { SetValue(CurvedBackgroundColorProperty, value); }
}
}
这是Android的渲染器:
[assembly: ExportRenderer(typeof(CurvedCornersLabel), typeof(CurvedCornerLabelRenderer))]
namespace CarouselDemo.Droid
{
public class CurvedCornerLabelRenderer:LabelRenderer
{
private GradientDrawable _gradientBackground;
protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
base.OnElementChanged(e);
var view = (CurvedCornersLabel)Element;
if (view == null) return;
// creating gradient drawable for the curved background
_gradientBackground = new GradientDrawable();
_gradientBackground.SetShape(ShapeType.Rectangle);
_gradientBackground.SetColor(view.CurvedBackgroundColor.ToAndroid());
// Thickness of the stroke line
_gradientBackground.SetStroke(4, view.CurvedBackgroundColor.ToAndroid());
// Radius for the curves
_gradientBackground.SetCornerRadius(
DpToPixels(this.Context,
Convert.ToSingle(view.CurvedCornerRadius)));
// set the background of the label
Control.SetBackground(_gradientBackground);
}
/// <summary>
/// Device Independent Pixels to Actual Pixles conversion
/// </summary>
/// <param name="context"></param>
/// <param name="valueInDp"></param>
/// <returns></returns>
public static float DpToPixels(Context context, float valueInDp)
{
DisplayMetrics metrics = context.Resources.DisplayMetrics;
return TypedValue.ApplyDimension(ComplexUnitType.Dip, valueInDp, metrics);
}
}
}
这是Xaml:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="CarouselDemo.LabelViewDemo"
xmlns:mr="clr-namespace:MR.Gestures;assembly=MR.Gestures"
xmlns:local="clr-namespace:CarouselDemo;assembly=CarouselDemo"
Padding="10,20,10,10">
<StackLayout Padding="20">
<Label Text="Card 1"
HeightRequest="100"
BackgroundColor="LightGoldenrodYellow"
x:Name="card1"
/>
<local:CurvedCornersLabel Text="Card 2"
HeightRequest="100"
BackgroundColor="LightBlue"
x:Name="card2"
Margin="0,-40,0,0"
CurvedCornerRadius="15"
></local:CurvedCornersLabel>
</StackLayout>
</ContentPage>
有什么想法吗?
答案 0 :(得分:0)
所以我找到了解决方案。首先,我将自定义渲染器中的背景颜色更改为红色,这显示红色的圆角,但叠加层中有蓝色方角。一旦我删除了&#34; LightBlue&#34;从Xaml中通过自定义渲染器设置颜色!