首页 > 解决方案 > 绘制具有相对位置和比例的三角形

问题描述

我的老师问我如何为用户控件绘制一个三角形,其中位置是相对的,而我在使用 fillPolygon 并获取窗口的实际大小时遇到​​了问题。他给了我一个公式,但我不明白我需要如何应用它。我会很感激一些帮助,我很迷茫。谢谢

老师的公式:公式

这是我的错误代码,您可以看到公式未应用:

using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MisControles
{
    public partial class ControlVolumen: UserControl
    {

        int ancho;
        int alto;
        Color fondo;
        Color color1;
        Color color2;
        Color color3;

        public ControlVolumen()
        {
            InitializeComponent();
            valor = 0;
            fondo = Color.Empty;
            color1 = Color.Green;
            color2 = Color.Yellow;
            color3 = Color.Red;
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            Graphics g = e.Graphics;
            Brush b = new SolidBrush(fondo);
            Point p0 = new Point(0, 0);
            Point p1 = new Point(this.Width);
            Point p2 = new Point(this.Height);
            g.FillPolygon(fondo, new Point[] {p0,p1,p2});
        }
    }
}

标签: c#

解决方案


创建并构建 Volume UserControl 后,您可以修改 volume bij 将 Valor 定义为属性。

public partial class VolumeControl : UserControl
{
    private int valor;
    public int Valor
    {
        get { return valor; }
        set { valor = value; this.Refresh(); }
    }
    public VolumeControl()
    {
        InitializeComponent();
    }
    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        var graphics = e.Graphics;
        var brush = new SolidBrush(Color.Blue);
        //calculate width and height based on percentage provided
        int ancho = this.Width * Valor/100;
        int alto = this.Height * Valor/100;

        // Graphic origin is upper-left corner.
        Point p0 = new Point(0, this.Height);
        Point p1 = new Point(ancho, this.Height);
        Point p2 = new Point(ancho, this.Height-alto);
        graphics.FillPolygon(brush, new Point[] { p0, p1, p2 });
    }
}

现在将新的 numericUpDownControl 和 VolumeControl 添加到 WindowsForm。 在此处输入图像描述

当 numericUpDown 改变时更新 VolumeControl。 在此处输入图像描述


推荐阅读