You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin带文字的SVG图片按钮设置SVG尺寸及使用Path路径方法

问题解答

一、SVG尺寸调整方案

你定义的TargetType="Image"样式不生效的原因是:Button的Image属性接收的是ImageSource类型对象,并非直接渲染外部定义的Image控件,全局Image样式无法作用到Button内部渲染图标用的内置Image实例。
最简单的解决方法是直接使用Button原生提供的ImageWidth和ImageHeight属性调整图标尺寸:

方法1:直接给单个Button加属性

<Button Text=" test" 
        BackgroundColor="Wheat" 
        BorderRadius="20" 
        TextColor="red"
        ImageWidth="50"
        ImageHeight="50">
    <Button.Image>
        <OnPlatform x:TypeArguments="FileImageSource" Android="home.svg" iOS="home.svg"/>
    </Button.Image>
</Button>

方法2:写到Button样式里全局生效

<Style TargetType="Button">
    <Setter Property="HorizontalOptions" Value="FillAndExpand"/>
    <!-- 统一设置所有按钮的图标尺寸 -->
    <Setter Property="ImageWidth" Value="50"/>
    <Setter Property="ImageHeight" Value="50"/>
</Style>

二、Button内部插入Path矢量路径的实现

Xamarin.Forms原生Button不支持直接嵌套Path作为内容,你可以通过自定义可点击布局的方式实现同等效果,还能更灵活控制内容排版:

<Frame BackgroundColor="Wheat" 
       CornerRadius="20" 
       HasShadow="False"
       HorizontalOptions="FillAndExpand">
    <StackLayout Orientation="Horizontal" 
                 HorizontalOptions="Center"
                 Spacing="8"
                 Padding="16,10">
        <Path Data="M185.255 512c-76.201 ....." 
              Fill="Red"
              WidthRequest="50"
              HeightRequest="50"/>
        <Label Text="test" 
               TextColor="Red"
               VerticalTextAlignment="Center"/>
    </StackLayout>
    <Frame.GestureRecognizers>
        <!-- 绑定点击事件实现按钮逻辑 -->
        <TapGestureRecognizer Tapped="OnCustomButtonClicked"/>
    </Frame.GestureRecognizers>
</Frame>

上述代码用Frame模拟原生按钮的外观,横向布局排列Path和文字,点击手势实现交互逻辑,完全可以替代原生Button的功能。如果需要按压态高亮效果,可以搭配视觉状态管理器实现。

内容的提问来源于stack exchange,提问作者Oleksii

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 05:15:02