我正在尝试创建一个支持同时添加文本和图像(自定义图像)的条目。现在,我正在尝试在macOS中实现这一目标。
到目前为止,我要做的是创建一个自定义控件,其中有一个图像列表,如果将新图像添加到条目中,则将其添加到其中。添加后,其想法是使其位于最后一个文本(或图像)的右侧。
控制:
public class ChatEntry : Entry
{
public ChatEntry()
{
this.HeightRequest = 50;
}
public static readonly BindableProperty ImageProperty =
BindableProperty.Create(nameof(Images), typeof(List<string>), typeof(ChatEntry), string.Empty);
public static readonly BindableProperty LineColorProperty =
BindableProperty.Create(nameof(LineColor), typeof(Xamarin.Forms.Color), typeof(ChatEntry), Color.White);
public static readonly BindableProperty ImageHeightProperty =
BindableProperty.Create(nameof(ImageHeight), typeof(int), typeof(ChatEntry), 40);
public static readonly BindableProperty ImageWidthProperty =
BindableProperty.Create(nameof(ImageWidth), typeof(int), typeof(ChatEntry), 40);
public Color LineColor
{
get { return (Color)GetValue(LineColorProperty); }
set { SetValue(LineColorProperty, value); }
}
public int ImageWidth
{
get { return (int)GetValue(ImageWidthProperty); }
set { SetValue(ImageWidthProperty, value); }
}
public int ImageHeight
{
get { return (int)GetValue(ImageHeightProperty); }
set { SetValue(ImageHeightProperty, value); }
}
public List<string> Images
{
get { return (List<string>)GetValue(ImageProperty); }
set { SetValue(ImageProperty, value); }
}
}
MacOS渲染器:
[assembly: ExportRenderer(typeof(ChatEntry), typeof(ChatEntryRenderer))]
namespace Project.MacOS.Renderers
{
public class ChatEntryRenderer : EntryRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
if (e.OldElement != null || e.NewElement == null)
return;
var element = (ChatEntry)this.Element;
var textField = this.Control;
if (element.Images != null)
{
// TODO : Logic GetImageView
}
CALayer bottomBorder = new CALayer
{
Frame = new CGRect(0.0f, element.HeightRequest - 1, this.Frame.Width, 1.0f),
BorderWidth = 2.0f,
BorderColor = element.LineColor.ToCGColor()
};
textField.Layer.AddSublayer(bottomBorder);
textField.Layer.MasksToBounds = true;
}
private NSView GetImageView(string imagePath, int height, int width)
{
var uiImageView = new NSImageView()
{
Frame = new RectangleF(0, 0, width, height)
};
uiImageView.Image = NSImage.ImageNamed(imagePath);
NSView objLeftView = new NSView(new System.Drawing.Rectangle(0, 0, width + 10, height));
objLeftView.AddSubview(uiImageView);
return objLeftView;
}
}
}
我现在面临的问题是将这一切捆绑在一起。我创建了一个GetImageView
可以返回NSView的位置,但是我不确定如何将其合并到前一个字符(或图像)的右侧,我不确定,需要一些指导。
在介绍所有内容之前,我想说Xamarin for MacOS仍在预览中,对于Entry,仍有一些功能有待开发,并可能影响您的应用程序,如果您要发布应用程序,则应仔细考虑并测试。您可以在此处找到输入状态
如果我正确理解了您的问题,则您正在尝试创建一个自定义条目,该条目可以将文本和图像放入其中,如下所示:
文字[IMG1] abc [IMG2] ...
这可能会给您带来一些想法:如何实现以图片为中心的标签。
它利用NSTextAttachment来保存图像,并利用NSMutableAttributedString] 4来保存条目中的整个字符串。区别在于,它仅包含一个图像,但条目中将包含多个图像,因此您可能需要一个字典来将字符串中的占位符与实际图像进行映射。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句