我被告知不能使这段代码的边框宽度小:
<Frame Grid.Column="0" CornerRadius="5" OutlineColor="Black">
<Label x:Name="faveIconLabel"
Style="{StaticResource mediumIcon}"
Margin="0,2,0,0"
HorizontalOptions="Fill"
FontFamily="FontAwesome"
VerticalOptions="Center"
VerticalTextAlignment="Center" />
</Frame>
有没有办法让框架或其他东西有边框宽度设置和半径设置?我想做的是让这个适用于iOS和Android,所以我可能需要使用自定义渲染器。
答案 0 :(得分:2)
您是对的,您可以使用自定义渲染器实现此目的:
第1步:创建新的Frame
班级:
public class RoundedCornerFrame : Frame
{
}
第2步:创建Android CustomRenderer:
using Android.Content;
using Android.Graphics;
using VerySimpleSample;
using VerySimpleSample.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(RoundedCornerFrame), typeof(RoundedCornerFrameRenderer))]
namespace VerySimpleSample.Droid
{
public class RoundedCornerFrameRenderer : FrameRenderer
{
public override void Draw(Canvas canvas)
{
base.Draw(canvas);
DrawOutline(canvas, canvas.Width, canvas.Height, Element.CornerRadius; //set corner radius
}
void DrawOutline(Canvas canvas, int width, int height, float cornerRadius)
{
using (var paint = new Paint { AntiAlias = true })
using (var path = new Path())
using (Path.Direction direction = Path.Direction.Cw)
using (Paint.Style style = Paint.Style.Stroke)
using (var rect = new RectF(0, 0, width, height))
{
float rx = Context.ToPixels(cornerRadius);
float ry = Context.ToPixels(cornerRadius);
path.AddRoundRect(rect, rx, ry, direction);
paint.StrokeWidth = 1f; //set outline stroke
paint.SetStyle(style);
paint.Color = Element.OutlineColor.ToAndroid(); //set outline color
canvas.DrawPath(path, paint);
}
}
}
}
第3步:创建iOS CustomRenderer:
using System;
using Xamarin.Forms.Platform.iOS;
using Xamarin.Forms;
using UIKit;
using CoreGraphics;
[assembly: ExportRenderer(typeof(Frame), typeof(RoundedCornerFrameRenderer ))]
namespace VerySimpleSample.Droid
{
public class RoundedCornerFrameRenderer : FrameRenderer
{
public RoundedCornerFrameRenderer ()
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Frame> e)
{
base.OnElementChanged(e);
if (Element != null)
{
// needed because of a bug in Xamarin that doesn't set the color
// https://bugzilla.xamarin.com/show_bug.cgi?id=44600
// https://forums.xamarin.com/discussion/76737/xamarin-color-same-value-different-tone-in-ios
Layer.BackgroundColor = ToCGColor(Element.BackgroundColor);
}
}
public static CGColor ToCGColor(Color color)
{
return new CGColor(CGColorSpace.CreateSrgb(), new nfloat[] { (float)color.R, (float)color.G, (float)color.B, (float)color.A });
}
}
}
第4步:在xaml中使用RoundedCornerFrame
:
<local:RoundedCornerFrame Grid.Column="0" Grid.Row="0" Margin="5, 5, 0, 0" OutlineColor="#0f8217" CornerRadius="5">
<Label Text="Hello"/>
</local:RoundedCornerFrame>
这就是它的样子:
另一个有用的提示是,您可以根据需要使用Padding
更改外观。这是Padding="5"
控件上的CoundedCornerFrame
: