将PointF []形状保存为图像

时间:2017-08-06 22:57:37

标签: c# image bitmap polygon

我有一个用户控件制作PointF[]三角形(用作轨迹栏的滑块)。

double hypotenuse;
double finalPoint;

public PointF Target { get; set; }
public PointF PointB { get; set; }
public PointF PointC { get; set; }

public PointF[] triangle = { new Point(0, 0), new Point(0, 0), new Point(0, 0) };

public TriangleSliderUC()
{
    InitializeComponent();
    SetStyle(ControlStyles.AllPaintingInWmPaint, true);
    SetStyle(ControlStyles.OptimizedDoubleBuffer, true);  

    PropertyConstructor();
    PointConstructor();

    Paint += new PaintEventHandler(TriangleSliderUC_Paint);
}

public void PointConstructor()
{
    Target = new PointF((int)finalPoint, (int)(hypotenuse * 0.5f));
    PointB = new PointF(0, 0);
    PointC = new PointF(0, (int)hypotenuse);

    triangle[0] = Target;
    triangle[1] = PointB;
    triangle[2] = PointC;
}

void TriangleSliderUC_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.FillPolygon(Brushes.Orange, triangle);
}

为了将它用作轨迹栏的拇指,我想将创建的三角形保存为位图,这样每次移动时都不必重新绘制。

我该怎么做?

另外,有没有更好的方法来构建我的代码?我是C#的新手,在OOP生锈了。

1 个答案:

答案 0 :(得分:0)

这是一个简单的例子,使用我能看到的当前代码。它可能不是你已经开发的东西的直接替代品,但应该给你一些想法。

我已经制作了HypotenuseFinalPoint公共主题,这些公共主题会写入私有变量,但也会调用更新三角形图像。 UpdateTriangle创建一个与控件尺寸相同的空白图像,然后像在PointConstructorPaint事件中一样绘制三角形。最后,它设置底层Control(PictureBox)的Image属性。

public class TriangleSliderUC : PictureBox
{
    public double Hypotenuse
    {
        get { return hypotenuse; }
        set
        {
            hypotenuse = value;
            UpdateTriangle();
        }
    }
    public double FinalPoint
    {
        get { return finalPoint; }
        set
        {
            finalPoint = value;
            UpdateTriangle();
        }
    }

    private PointF[] triangle = { new Point(0, 0), new Point(0, 0), new Point(0, 0) };
    private double hypotenuse;
    private double finalPoint;

    public TriangleSliderUC()
    {
        UpdateTriangle();
    }

    public void UpdateTriangle()
    {
        triangle[0] = new PointF((int)finalPoint, (int)(hypotenuse * 0.5f));
        triangle[1] = new PointF(0, 0); 
        triangle[2] = new PointF(0, (int)hypotenuse);

        // Create a new image with the current control dimensions
        Bitmap image = new Bitmap(Width, Height);

        // Create a grahics object, draw the triangle
        var g = Graphics.FromImage(image);
        g.FillPolygon(Brushes.Orange, triangle);

        // Update the controls image with the newly created image
        this.Image = image;
    }
}

如果您希望缩放以适应可用空间,您可能还需要从UpdateTriangle事件添加对Resize功能的调用。

this.Resize += TriangleSliderUC_Resize;

private void TriangleSliderUC_Resize(object sender, EventArgs e)
{
    UpdateTriangle();
}