是的,你可以这样做,但你应该这样做吗?
下面是你代码需要的更改:
Bitmap b = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.Height);
pictureBox1.DrawToBitmap(b, pictureBox1.ClientRectangle);
Color colour = b.GetPixel(X, Y);
b.Dispose();
但是如果你想真正使用 PictureBox
的功能,比如它的 SizeMode
,那么必须给它一个真正的 Image
才能发挥作用。简单地在其背景上绘制并不相同。以下是分配真实位图的最小代码:
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事件!)
现在你可以进行测试,例如使用Label和鼠标:
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (pictureBox1.Image != null)
{
Bitmap bmp = new Bitmap(pictureBox1.Image);
Color colour = bmp.GetPixel(e.X, e.Y);
label1.Text = colour.ToString();
bmp.Dispose();
}
else
{
Bitmap bmp = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.Height);
pictureBox1.DrawToBitmap(bmp, pictureBox1.ClientRectangle);
Color colour = bmp.GetPixel(e.X, e.Y);
label1.Text += "ARGB :" + 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);
}