I'm working on a UWP app, and I'm creating my own UI components. Until now, I've been working with WinForms, and there's the OnPaint
method, which I could use to override how a custom component would be drawn. Now that I'm working with UWP, I was wondering if there is a similar method that I could use to draw custom components.
One of my OnPaint
methods used to look like this:
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));
}
}
UWP doesn't have a method like OnPaint
, but you can try using Win2D CanvasDraw in UWP User Control.
Right-click your project-> Select Add -> New Item -> Choose User Control
<Grid>
<canvas:CanvasControl Draw="CanvasControl_Draw" ClearColor="CornflowerBlue"/>
</Grid>
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);
}
}
<Grid>
<local:MyUserControl1/>
</Grid>