簡體   English   中英

C 中如何改變圖像的大小和改變在圖像特定部分的圖片框內繪制的矩形的大小#

[英]How to change the size of the image and change the size of the rectangle that was drawn inside the picture box on a specific part of the image in C #

如何更改圖像的大小和圖像內部繪制的矩形的大小,使矩形不丟失 x 和 y 的 position。 我做了以下代碼,但它沒有保留矩形的 position

int index3 = dataGridView1.CurrentCell.RowIndex;

        xxx = Convert.ToInt32(dataGridView1.Rows[index3].Cells[10].Value.ToString());
        yyy = Convert.ToInt32(dataGridView1.Rows[index3].Cells[11].Value.ToString());
        hhh = Convert.ToInt32(dataGridView1.Rows[index3].Cells[12].Value.ToString());
        www = Convert.ToInt32(dataGridView1.Rows[index3].Cells[13].Value.ToString());
        Rectangle r = new Rectangle(xxx, yyy, www, hhh);
        
        

        int newX = (int)(xxx+ (xxx*0.2));
        int newY = (int)(yyy +( yyy*0.2));

        int newWidth = (int)(r.Width +(r.Width*0.2));
        int newHeight = (int)(r.Height +(r.Height*0.2));

       
        picturModule.Size = new Size((int)(picturModule.Width+(picturModule.Width*0.2)),(int)(picturModule.Height+(picturModule.Height*0.2)));
         r = new Rectangle(newX, newY, newWidth, newHeight);
        
        Pen pen = new Pen(Color.GreenYellow, 4);
        picturModule.CreateGraphics().DrawRectangle(pen, r);

問題是在圖像上繪制矩形后更改圖像大小時,矩形沒有移動到正確的 X 和 Y 點,它的 position 發生變化。 我希望在更改圖像大小時,矩形的大小會發生變化並保持與開始點相同的點

好的。 您可以做的是將矩形的 position 和大小存儲為圖像/圖片框寬度/高度的“百分比”。 這可以使用RectangleF和浮點值來完成。

現在您可以使用這些“百分比”值並將它們乘以新的圖片框寬度/高度以獲得縮放的位置和大小。

這是一個例子:

在此處輸入圖像描述

生成 animation 的代碼:

public partial class Form2 : Form
{

    public Form2()
    {
        InitializeComponent();
    }

    private bool drawRect = false;
    private RectangleF rcF;

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        if (drawRect)
        {
            Point pt = new Point((int)(rcF.X * pictureBox1.Width),
                (int)(rcF.Y * pictureBox1.Height));
            Size sz = new Size((int)(rcF.Width * pictureBox1.Width),
                (int)(rcF.Height * pictureBox1.Height));
            e.Graphics.DrawRectangle(Pens.Black, new Rectangle(pt, sz));
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Rectangle initialRectangle = new Rectangle(new Point(300, 150), new Size(125, 50));
        PointF ptF = new PointF((float)initialRectangle.X / pictureBox1.Width,
            (float)initialRectangle.Y / pictureBox1.Height);
        SizeF szF = new SizeF((float)initialRectangle.Width / pictureBox1.Width,
            (float)initialRectangle.Height / pictureBox1.Height);
        rcF = new RectangleF(ptF, szF);
        drawRect = true;
        pictureBox1.Invalidate();
    }

    private void pictureBox1_SizeChanged(object sender, EventArgs e)
    {
        pictureBox1.Invalidate();
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM