Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
914 views
in Technique[技术] by (71.8m points)

c# - How to create PictureBoxes with shapes based on a Picture

Problem: I have pictures of objects on a white background. I need PictureBoxes that do have the exact shape of these objects, but I do not know how these objects look like a priori.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

My solution to this is a new class:

class ShapedPictureBox : PictureBox
{
    public ShapedPictureBox()
    {

    }

    public Color transparentColor = Color.White;

    public void updateShape()
    {
    if(this.Image = null) return;
    Bitmap bitmap = new Bitmap(this.Image);
    System.Drawing.Drawing2D.GraphicsPath graphicsPath = new System.Drawing.Drawing2D.GraphicsPath();
    for(int x = 0; x < this.Image.Width; x++)
        for(int y = 0; y < this.Image.Height; y++)
            if(transparentColor != bitmap.GetPixel(x, y))
                graphicsPath.AddRectangle(new Rectangle(new Point(x, y), new Size(1, 1)));
    this.Region = new Region(graphicsPath);
    }
}

whenever you invalidate the object the shape will be recreated. I am aware that this solution is not effective at all, but it was the only I found.. I hope it helps someone..

If you have better/more efficient ideas, please let me know.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...