是的你可以,但应该你?
这里是你的代码需要改变:
Bitmap b = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.Height);
pictureBox1.DrawToBitmap(b, pictureBox1.ClientRectangle);
Color colour = b.GetPixel(X, Y);
b.Dispose();
但真的是有各地给予PictureBox
真正Image
,如果你想要做真正的工作,它与地方工作,如果你想这意味着没有办法使用它的可能性,例如其SizeMode
。
简单地画在它的背景上是不一样的。为此你可以(也应该)简单地使用Panel。下面是一个最小的代码来获得分配一个真正的位图:
public Form1()
{
InitializeComponent();
pictureBox1.Image = new Bitmap(pictureBox1.ClientSize.Width,
pictureBox1.ClientSize.Height);
using (Graphics graphics = Graphics.FromImage(pictureBox1.Image))
{
graphics.FillRectangle(Brushes.CadetBlue, 0, 0, 99, 99);
graphics.FillRectangle(Brushes.Beige, 66, 55, 66, 66);
graphics.FillRectangle(Brushes.Orange, 33, 44, 55, 66);
}
}
但是,如果你真的不想要分配的图像可以使PictureBox
绘制自身到一个真正的Bitmap
。请注意,您需要在Paint
事件中绘制矩形等,才能使用! (其实你也必须使用Paint
事件也是出于其他原因!)
现在你可以测试任何一种方式,例如,使用标签和鼠标:
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (pictureBox1.Image != null)
{ // the 'real thing':
Bitmap bmp = new Bitmap(pictureBox1.Image);
Color colour = bmp.GetPixel(e.X, e.Y);
label1.Text = colour.ToString();
bmp.Dispose();
}
else
{ // just the background:
Bitmap bmp = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.Height);
pictureBox1.DrawToBitmap(bmp, pictureBox1.ClientRectangle);
Color colour = bmp.GetPixel(e.X, e.Y);
label1.Text = colour.ToString();
bmp.Dispose();
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.FillRectangle(Brushes.DarkCyan, 0, 0, 99, 99);
e.Graphics.FillRectangle(Brushes.DarkKhaki, 66, 55, 66, 66);
e.Graphics.FillRectangle(Brushes.Wheat, 33, 44, 55, 66);
}
您给出的代码的第一部分足以达到我的目的,但您的其他回复也是很好的建议。感谢您花时间回答我的问题。 – user3765211