Drawing Colors in a picturebox?

心不动则不痛 提交于 2019-12-31 04:15:11

问题


In C# i have a picturebox. i would like to draw 4 colors. The default will be white, red, green, blue. How do i draw these 4 colors stritched in this picbox? or should i have 4 picbox? in that case how do i set the rgb color?


回答1:


You need to specify what it is you would specifically like to draw. You can't draw a red - that makes no sense. You can, however, draw a red rectangle at location (0,0) which is 100 pixels tall and 100 wide. I will answer what I can, however.

If you want to set the outline of a shape to a specific color, you would create a Pen object. If you want to fill a shape with a color, however, then you would use a Brush object. Here's an example of how you would draw a rectangle filled with red, and a rectangle outlined in green:

private void pictureBox_Paint(object sender, PaintEventArgs e)
{
    Graphics graphics = e.Graphics;

    Brush brush = new SolidBrush(Color.Red);
    graphics.FillRectangle(brush, new Rectangle(10, 10, 100, 100));

    Pen pen = new Pen(Color.Green);
    graphics.DrawRectangle(pen, new Rectangle(5, 5, 100, 100));
}



回答2:


Add a PictureBox to the form, create an event handler for the paint event, and make it look like this:

private void PictureBox_Paint(object sender, PaintEventArgs e)
{
    int width = myPictureBox.ClientSize.Width / 2;
    int height = myPictureBox.ClientSize.Height / 2;

    Rectangle rect = new Rectangle(0, 0, width, height);
    e.Graphics.FillRectangle(Brushes.White, rect);
    rect = new Rectangle(width, 0, width, height);
    e.Graphics.FillRectangle(Brushes.Red, rect);
    rect = new Rectangle(0, height, width, height);
    e.Graphics.FillRectangle(Brushes.Green, rect);
    rect = new Rectangle(width, height, width, height);
    e.Graphics.FillRectangle(Brushes.Blue, rect);
}

This will divide the surface into 4 rectangles and paint each of them in the colors White, Red, Green and Blue.




回答3:


If you want to use non-predefined colors, then you need to get a Color object from the static method Color.FromArgb().

int r = 100;
int g = 200;
int b = 50;

Color c = Color.FromArgb(r, g, b);

Brush brush = new SolidBrush(c);
//...

Best Regards
Oliver Hanappi



来源:https://stackoverflow.com/questions/1113437/drawing-colors-in-a-picturebox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!