我需要使用PCL项目在Xamarin表单中对Image进行文本叠加,如下图所示
我创建了替换布局来执行此操作,任何人都可以建议我如何格式化文本?
var myLabel = new Label()
{
Text = "Hello World",
Font = Font.SystemFontOfSize(20),
TextColor = Color.White,
XAlign = TextAlignment.Center,
YAlign = TextAlignment.Center
};
var stack = new StackLayout
{
Children = {myLabel}
};
var slayout = new ContentView
{
BackgroundColor = new Color(0,0,0,.5),
Content = stack
};
var myImage = new Image()
{
Source = "deal1.png"
};
RelativeLayout layout = new RelativeLayout();
layout.Children.Add(myImage,
Constraint.Constant(0),
Constraint.Constant(0),
Constraint.RelativeToParent((parent) => { return parent.Width; }),
Constraint.RelativeToParent((parent) => { return parent.Height; }));
layout.Children.Add(slayout,
Constraint.Constant(0),
Constraint.Constant(0),
Constraint.RelativeToParent((parent) => { return parent.Width; }),
Constraint.RelativeToParent((parent) => { return parent.Height; }));
答案 0 :(得分:1)
我会写一些看起来像这样的东西(根据覆盖文本的不同元素自定义更多可绑定属性和标签,以及标签背景颜色和不透明度的可绑定属性)。
public class OverlayedImage : ContentView
{
public static readonly BindableProperty SourceProperty = BindableProperty.Create(nameof(Source), typeof(ImageSource), typeof(OverlayedImage));
public ImageSource Source
{
get { return (ImageSource)GetValue(SourceProperty); }
set { SetValue(SourceProperty, value); }
}
public static readonly BindableProperty TextProperty = BindableProperty.Create(nameof(Text), typeof(string), typeof(OverlayedImage));
public string Text
{
get { return (string)GetValue(SourceProperty); }
set { SetValue(SourceProperty, value); }
}
protected override void OnPropertyChanged(string propertyName = null)
{
if (propertyName == SourceProperty.PropertyName)
{
_image.Source = Source;
}
else if (propertyName == TextProperty.PropertyName)
{
_label.Text = Text;
}
else
base.OnPropertyChanged(propertyName);
}
private readonly Image _image =new Image();
private readonly Label _label = new Label();
public OverlayedImage()
{
var abs = new AbsoluteLayout();
abs.Children.Add(_image, new Rectangle(0, 0 , 1 , 1), AbsoluteLayoutFlags.All);
abs.Children.Add(_label, new Rectangle(0, 1, 1, 0.5), AbsoluteLayoutFlags.All);
Content = abs;
}
}