[英]How to get all the pixel values inside a rectangle in C#
我正在開發一個程序來獲取矩形內的所有像素。 有一個圖像控件,用戶可以單擊其中的一部分。 當用戶單擊特定位置時,將繪制一個矩形。 我想獲取該矩形內的所有像素。 我現在要繪制矩形。 但是我無法獲得所有像素值。 請在下面找到繪制矩形的代碼段。
private void panel1_Paint(object sender, PaintEventArgs e)
{
foreach (var rectKey in rectangles.Keys)
{
using (var pen = new Pen(rectKey)) //Create the pen used to draw the rectangle (using statement makes sure the pen is disposed)
{
//Draws all rectangles for the current color
//Note that we're using the Graphics object that is passed into the event handler.
e.Graphics.DrawRectangles(pen, rectangles[rectKey].ToArray());
}
}
}
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
Color c = System.Drawing.Color.GreenYellow ; //Gets a color for which to draw the rectangle
//Adds the rectangle using the color as the key for the dictionary
if (!rectangles.ContainsKey(c))
{
rectangles.Add(c, new List<Rectangle>());
}
rectangles[c].Add(new Rectangle(e.Location.X - 12, e.Location.Y - 12, 25, 25)); //Adds the rectangle to the collection
}
//Make the panel repaint itself.
panel1.Refresh();// Directs to panel1_Paint() event
rectangles.Clear();
}
在這種情況下,您將不得不使用Bitmap
而不是圖形對象。
位圖具有一種獲取某個位置像素的方法
Bitmap bmp = Bitmap.FromFile("");
// Get the color of a pixel within myBitmap.
Color pixelColor = bmp.GetPixel(50, 50);
要讀取矩形內的所有像素,可以使用bmp.LockBits
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.