0
我創建了一個自定義渲染器來在標籤後面創建圓形,就像徽章一樣。Xamarin Round Label自定義渲染器不工作
CircleView.cs(PCL)
public partial class CircleView : BoxView
{
public static readonly BindableProperty CornerRadiusProperty = BindableProperty.Create(nameof(CornerRadius), typeof(double), typeof(CircleView), 0.0);
public double CornerRadius
{
get { return (double)GetValue(CornerRadiusProperty); }
set { SetValue(CornerRadiusProperty, value); }
}
public CircleView()
{
InitializeComponent();
}
}
CircleViewRenderer.cs(機器人)
[assembly: ExportRenderer(typeof(CircleView), typeof(CircleViewRenderer))]
namespace TestApp.Droid
{
public class CircleViewRenderer : BoxRenderer
{
private float _cornerRadius;
private RectF _bounds;
private Path _path;
protected override void OnElementChanged(ElementChangedEventArgs<BoxView> e)
{
base.OnElementChanged(e);
if (Element == null)
{
return;
}
var element = (CircleView)Element;
_cornerRadius = TypedValue.ApplyDimension(ComplexUnitType.Dip, (float)element.CornerRadius, Context.Resources.DisplayMetrics);
}
protected override void OnSizeChanged(int w, int h, int oldw, int oldh)
{
base.OnSizeChanged(w, h, oldw, oldh);
if (w != oldw && h != oldh)
{
_bounds = new RectF(0, 0, w, h);
}
_path = new Path();
_path.Reset();
_path.AddRoundRect(_bounds, _cornerRadius, _cornerRadius, Path.Direction.Cw);
_path.Close();
}
public override void Draw(Canvas canvas)
{
canvas.Save();
canvas.ClipPath(_path);
base.Draw(canvas);
canvas.Restore();
}
}
}
CircleViewRenderer.cs(IOS)
[assembly: ExportRenderer(typeof(CircleView), typeof(CircleViewRenderer))]
namespace TestApp.iOS
{
public class CircleViewRenderer : BoxRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<BoxView> e)
{
base.OnElementChanged(e);
if (Element == null)
return;
Layer.MasksToBounds = true;
Layer.CornerRadius = (float)((CircleView)Element).CornerRadius/2.0f;
}
}
}
在XAML我試圖這樣的:
<Grid>
<customRenderer:CircleView x:Name="BadgeCircle" HeightRequest="16" WidthRequest="16" CornerRadius="16" VerticalOptions="Center" HorizontalOptions="Center" /><Label x:Name="BadgeLabel" TextColor="White" VerticalOptions="Center" HorizontalOptions="Center" VerticalTextAlignment="Center" HorizontalTextAlignment="Center" FontSize="10"/>
</Grid>
但它沒有顯示任何東西。初始化錯誤顯示在CircleView上,所以我評論了InitializeComponent(); 我在這裏失蹤了什麼?
能否請您嘗試取消對'的InitializeComponent() '並建立項目? –
它不工作,並給出錯誤 –
請嘗試清除項目並重建它。如果仍然有錯誤,你可以分享一個基本的演示嗎? –