繁体   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