我有这个自定义渲染器,我只想在文本边界框大于按钮的情况下调整文本大小以适应按钮的边界矩形。
我想要做的是在按钮的背景上“手动”绘制文本,而不允许按钮本身绘制文本。
如果不使用不同类型的视图来伪造按钮,这是否可行?
我可以从渲染器以某种方式拦截FontSize属性设置器,因此我可以将其值存储在某些ivar中,同时将零传递给按钮,这样它就不会绘制文本了吗?
public class AutoTextSizeButtonRenderer : ButtonRenderer
{
private float fontSize = 0;
private static float EPSILON = 0.1f;
public AutoTextSizeButtonRenderer(Context context) : base(context)
{
SetWillNotDraw(false);
}
protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
Button button = Element as Button;
if (Math.Abs(button.FontSize - 1) > EPSILON && Math.Abs(button.FontSize - fontSize) > EPSILON) {
fontSize = (float)button.FontSize;
button.FontSize = 1;
}
//Draw(new Canvas());
}
public override void Draw(Canvas canvas)
{
base.Draw(canvas);
Button button = Element as Button;
string text = button.Text;
if (text != null)
{
TextPaint paint = new TextPaint();
//paint.SetTypeface(Typeface.DefaultBold);
paint.AntiAlias = true;
Rect bounds = new Rect();
Paint.FontMetrics metrics = null;
DisplayMetrics displayMetrics = new DisplayMetrics();
Display.GetMetrics(displayMetrics);
float scaledDensity = displayMetrics.ScaledDensity;
float textSize = fontSize;
while(textSize >= 0)
{
paint.TextSize = scaledDensity * textSize;
paint.GetTextBounds(text, 0, text.Length, bounds);
metrics = paint.GetFontMetrics();
if (bounds.Width() < MeasuredWidth && (metrics.Bottom - metrics.Top) < MeasuredHeight) {
break;
}
textSize--;
}
paint.Color = button.TextColor.ToAndroid();
canvas.DrawText(
text,
0.5f * MeasuredWidth - bounds.Left - 0.5f * bounds.Width(),
0.5f * MeasuredHeight - metrics.Ascent - 0.5f * (metrics.Bottom - metrics.Top),
paint);
}
}
}
我如何检测OnElementPropertyChanged中FontSize值的变化
当您更改Xamarin.Forms.Button
FontSize
属性时,您可以在OnElementPropertyChanged
方法中检测到此更改,如下所示:
protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == Xamarin.Forms.Button.FontSizeProperty.PropertyName)
System.Diagnostics.Debug.WriteLine("FontSizeProperty has changed!");
}
获取Button
FontSize
值:
protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == Xamarin.Forms.Button.FontSizeProperty.PropertyName)
System.Diagnostics.Debug.WriteLine("FontSizeProperty has changed!");
System.Diagnostics.Debug.WriteLine("Element.FontSize == " + Element.FontSize);
}