XAML 什么是UWP应用程序中的OnPaint方法

fiei3ece  于 2023-06-19  发布在  其他
关注(0)|答案(1)|浏览(122)

我正在开发一个UWP应用程序,我正在创建我自己的UI组件。到目前为止,我一直在使用WinForms,有OnPaint方法,我可以使用它来覆盖定制组件的绘制方式。现在我正在使用UWP,我想知道是否有类似的方法可以用来绘制自定义组件。
我的一个OnPaint方法看起来像这样:

protected override void OnPaint(PaintEventArgs e)
        {
            int buttonHeight = Height;
            int buttonWidth = Width;

            int imgHeight = Height;
            int imgWidth = Height;
            int textPadding = (Height - FontHeight) / 2;
            int textStartX = imgWidth + textPadding;
            int textStartY = textPadding - 3; // Have to get rid of 3, otherwise it's off center
            

            Graphics g = e.Graphics;

            FillRoundedRectangle(g, new SolidBrush(ButtonColor()), new Rectangle(0, 0, Width, Height), 10); // Background

            if (ImageOnly == Mode.True)
            {
                g.DrawImage(Image, new Rectangle((buttonWidth / 2) - (imgWidth / 2), (buttonHeight / 2) - (imgHeight / 2), imgWidth, imgHeight));
            }
            else
            {
                g.DrawImage(Image, new Rectangle(0, 0, imgWidth, imgHeight));
                g.DrawString(Text, ButtonFont, new SolidBrush(Foreground), new Point(textStartX, textStartY));
            }
        }
yhqotfr8

yhqotfr81#

UWP没有像OnPaint这样的方法,但您可以尝试在UWP User Control中使用Win2D CanvasDraw

    • 右键单击您的项目->选择添加**->新建项目**->选择用户控件
MyUserControl1.xaml
<Grid>
    <canvas:CanvasControl Draw="CanvasControl_Draw" ClearColor="CornflowerBlue"/>
</Grid>
MyUserControl1.xaml.cs
public sealed partial class MyUserControl1 : UserControl
{
    public MyUserControl1()
    {
        this.InitializeComponent();

    }

    void CanvasControl_Draw(CanvasControl sender, CanvasDrawEventArgs args)
    {
        args.DrawingSession.DrawEllipse(155, 115, 80, 30, Colors.Black, 3);
        args.DrawingSession.DrawText("Hello, world!", 100, 100, Colors.Yellow);
    }
}
MainPage. xaml
<Grid>
   <local:MyUserControl1/>
</Grid>

相关问题