是的你可以,但應該你?
這裏是你的代碼需要改變:
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