[英]How do I get the Image location?
這是pictureBox1的paint事件中的代碼。 我需要找到變量mImage的位置。
if (null != mImage)
{
e.Graphics.DrawImage(mImage, theLocationOfImage);
}
mImage是圖像類型。 相反,我需要放置mImage的位置。 這就是我得到mImage的方式:
private void pictureBox1_MouseWheel(object sender, MouseEventArgs e)
{
Bitmap bmp = new Bitmap(pictureBox1.Image);
Bitmap bmp1 = GetPartOfImageInRect(bmp, mRect);
CalculateNewSizeFactor(e.Delta);
Image img1 = ResizeImage(bmp1,
new Size((int)(bmp1.Width * currentfactor),
(int)(bmp1.Height * currentfactor)));
mImage = img1;
pictureBox1.Invalidate();
}
mRect是我在pictureBox1上繪制的矩形。
編輯
這是我繪制矩形的方式:
private void DrawRectangle(Graphics e)
{
using (Pen pen = new Pen(Color.Red, 2))
{
e.DrawRectangle(pen, mRect);
}
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
mRect = new Rectangle(e.X, e.Y, 0, 0);
pictureBox1.Invalidate();
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
mRect = new Rectangle(mRect.Left, mRect.Top, e.X - mRect.Left, e.Y - mRect.Top);
pictureBox1.Invalidate();
}
}
這是調整大小圖像方法:
private Image ResizeImage(Image img, Size size)
{
return new Bitmap(img, size);
}
這是pictureBox1繪畫事件:
if (null != mImage)
{
e.Graphics.DrawImage(mImage, theLocationOfImage);
}
DrawRectangle(e.Graphics);
最后計算新的尺寸系數方法:
private void CalculateNewSizeFactor(int delta)
{
if (delta > 0 && factor < 2.5)
{
factor *= increment;
currentfactor = factor;
}
else if (delta < 0 && factor > 0.25)
{
factor /= increment;
currentfactor = factor;
}
}
我可以調整放大整個圖像的大小,但是我只想縮小繪制矩形的區域。
編輯
忘記添加此方法:
private Bitmap GetPartOfImageInRect(Bitmap source, Rectangle rect)
{
return source.Clone(rect, source.PixelFormat);
}
縮放時的問題是要縮放的矩形的縱橫比可能與整個圖像的縱橫比不同。 因此,您必須考慮兩種不同的情況。
// Calculate the size and position of the zoomed rectangle.
double zoomFactorX = picturBox1.Width / mRect.Width;
double zoomFactorY = picturBox1.Height / mRect.Height;
Size newSize;
Point newLocation;
if (zoomFactorX < zoomFactorY) { // Fit image portion horizontally.
newSize = new Size(picturBox1.Width, (int)Math.Round(zoomFactorX * mRect.Height));
// We have a top and a bottom padding.
newLocation = new Point(0, (picturBox1.Height - newSize.Height) / 2);
} else { // Fit image portion vertically.
newSize = new Size((int)Math.Round(zoomFactorY * mRect.Width), picturBox1.Height);
// We have a left and a right padding.
newLocation = new Point((picturBox1.Width - newSize.Width) / 2, 0);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.