如何在C#中设置图形颜色

时间:2016-11-12 04:18:32

标签: java c#

如何在c#中设置图形颜色?
SetColor方法无效。

如何将以下Java代码转换为C#?

private Graphics g1;

g1.setColor(Color.getHSBColor(h, 0.8f, b)); 
Color col = Color.getHSBColor(h, 0.8f, b);
int red = col.getRed();
int green = col.getGreen();
int blue = col.getBlue();

1 个答案:

答案 0 :(得分:0)

The drawing model in C# is slightly different. Instead of setting resources, like color, on a graphic object, you create resources, such as Pen, or Brush that have properties on them, like Color. You then use those objects to draw on an image.

Graphics g = Graphics.FromImage(someBitMap); //create a graphics object for an existing BitMap
Color c = new Color(255,0,0); //a "red" color
Pen p = new Pen(c); //create a Pen using the Red color from earlier
p.Width = 5; //Pen is 5 pixels wide

g.DrawLine(p, 0,0,100,100); //draw a diagonal line

//Get rbg values.
int r = c.R;
int g = c.G;
int b = c.B;

//It is VERY important to call `.Dispose()` on GDI objects.  They contain unmanaged system resources that can, and will, leak if you don't.
g.Dispose()
p.Dispose()

It looks like you might be trying to convert a color from the HSB color-space to RGB. Unfortunately, that isn't natively supported in .NET. The following blog post has some code that can do that for you: https://blogs.msdn.microsoft.com/cjacks/2006/04/12/converting-from-hsb-to-rgb-in-net/