PictureBox 에 그린 사각형을 실제 불러온 Image 좌표로 변환하기

 

Rectangle rectRoi = new Rectangle();  // PictureBox 에 그려진 Rectangle

// (PictureBox 에 Rectangle 그리기 : e2hwan.tistory.com/5?category=868480)

Rectangle rectOnImg = new Rectangle();  // 실제 이미지 좌표로 변환될 Rectangle

 

Rectangle TransRectPic2Img(Rectangle rectRoi)
{

    // PictureBox 에 보여지는 실제 이미지 Scale 을 계산, 가로*세로중 작은 값으로 계산됨
    float imageScale = Math.Min((float)pictureBox.Width / (float)pictureBox.Image.Width,

                                    (float)pictureBox.Height / (float)pictureBox.Image.Height);

    // pictureBox 에 그려진 Image Size
    int scaledWidth = (int)(pictureBox.Image.Width * imageScale);
    int scaledHeight = (int)(pictureBox.Image.Height * imageScale);

    

    // pictureBox 의 그려진 Image 의 시작점(Offset)
    int imageX = (pictureBox.Width - scaledWidth) / 2;
    int imageY = (pictureBox.Height - scaledHeight) / 2;

 

    // 실제 Image 스케일로 변환된 Rectangle 의 시작점과 Width, Height
    rectOnImg.X = (int)((float)(rectRoi.X - imageX) / imageScale);
    rectOnImg.Y = (int)((float)(rectRoi.Y - imageY) / imageScale);
    rectOnImg.Width = (int)((float)rectRoi.Width / imageScale);
    rectOnImg.Height = (int)((float)rectRoi.Height / imageScale);

 

    return rectOnImg;

}

+ Recent posts