如何在Xamarin Forms的Label控件中嵌入图片,求非HTML视图实现方案
Xamarin Forms Label控件内嵌图片实现方案(非HTML视图)
方案1:修复自定义字体图标实现(优先推荐,性能最优)
你之前的字体图标思路是完全可行的,失败大概率是字体配置或者调用方式不对,正确实现步骤如下:
- 放置字体文件并配置属性
- Android:将ttf文件放到
Assets目录,文件属性设置为AndroidAsset - iOS:将ttf文件放到
Resources目录,文件属性设置为BundleResource,同时在Info.plist的UIAppFonts数组中添加你的字体文件名(例如customicon.ttf) - 共享库内嵌:将ttf放到.NET Standard项目任意目录,属性设置为
Embedded resource,通过ExportFont特性全局注册
- Android:将ttf文件放到
- 声明字体资源
在页面或全局的ResourceDictionary中添加字体映射,注意#后为字体的实际全称(不是文件名,可在ttf文件的属性详情中查看):<OnPlatform x:Key="CustomIconFont" x:TypeArguments="x:String"> <On Platform="Android" Value="customicon.ttf#Custom Icon Font" /> <On Platform="iOS" Value="Custom Icon Font" /> </OnPlatform> - Span中调用字体图标
替换为你图标对应的Unicode编码(转字体文件时会生成对应的编码对照表):<Label> <Label.FormattedText> <FormattedString> <Span Text="If you find this image " /> <Span Text="" FontFamily="{StaticResource CustomIconFont}" FontSize="16" /> <Span Text=" you win" /> </FormattedString> </Label.FormattedText> </Label>
方案2:自定义Label渲染器绘制内嵌图片(无需转换字体)
如果不想折腾字体转换,可以通过自定义渲染器直接在文本绘制时插入图片:
- 共享项目定义自定义Label控件,添加内嵌图片的绑定属性:
public class InlineImageLabel : Label { public static readonly BindableProperty InlineIconProperty = BindableProperty.Create(nameof(InlineIcon), typeof(ImageSource), typeof(InlineImageLabel)); public ImageSource InlineIcon { get => (ImageSource)GetValue(InlineIconProperty); set => SetValue(InlineIconProperty, value); } // 可扩展添加IconSize、InsertPosition等属性控制图片展示 }
- 分别在Android、iOS平台实现对应渲染器,计算文本中要插入图片的坐标点,在绘制文本的同时将图片渲染到目标位置即可,上层调用逻辑和原生Label一致。
方案3:布局拼接(实现成本最低,适配无复杂折行的场景)
如果你的文本长度较短、不需要跨折行展示,直接用横向布局拼接是最简单的方案:
<HorizontalStackLayout Spacing="3" VerticalOptions="Center"> <Label Text="If you find this image " VerticalTextAlignment="Center" /> <Image Source="image.png" WidthRequest="16" HeightRequest="16" /> <Label Text=" you win" VerticalTextAlignment="Center" /> </HorizontalStackLayout>
该方案无需自定义任何代码,全平台原生适配,仅不适用于长文本需要折行的场景。
内容的提问来源于stack exchange,提问作者Simone Pittiglio
相关产品推荐
相关产品推荐

