UIImageView. Zoom and Center to arbitrary rectangl

2019-03-06 23:04发布

There is simple iPad application. Views hierarchy is: Window - UIView - UIImageView UIImageView has loaded image which is bigger then screen size (i.e. 1280 x 2000 against 768 x 1004). I need to zoom in arbitrary rectangular part of image (fit it on the screen) and then center it on the screen. At the moment I do zooming in following way:

-(IBAction)posIt:(id)sender
{
    // rectangle size and origin in image's coordinates. Its received from out of application
    CGFloat x = 550.f;
    CGFloat y = 1006.f;
    CGFloat w = 719.f;
    CGFloat h = 850.f;

    CGSize frameSize = CGSizeMake(_imgView.image.size.width, _imgView.image.size.height);
    _imgView.frame = CGRectMakeWithParts(CGPointMake(0, 0), frameSize);

    // Calculate center manually because orientation changing
    CGPoint superCenter = CGPointMake(self.view.bounds.size.width/2, self.view.bounds.size.height/2);

    // delta is the factor between size of image size and device screen
    CGFloat delta = 768.f/w;

    // resizing UIImageView to fit rectangle on the screen
    frameSize = CGSizeMake(_imgView.image.size.width * delta, _imgView.image.size.height * delta);
    _imgView.frame = CGRectMakeWithParts(CGPointMake(0, 0), frameSize);

    // Here is I'm trying to calculate center of rectangle
    _imgView.center = CGPointMake(superCenter.x + (superCenter.x - (w/2)*delta - x * delta), superCenter.y + (superCenter.y - (h/2)*delta - y * delta));
}

UIImageView's ContentMode parameter is AspectFit. I believe that to move one point (UIImageView's center) to another one (in order to move rectangle to the center of the superView) I shall use following formula:

newX = oldX + oldX - rectCenterX;

newY = oldY + oldY - rectCenterY;

Since UIImageView is scaled with delta factor, rectCenterX and rectCenterY should be multiplied with same delta. But I'm wrong. Rectangles centers jump out from superView center.

Is there exists some way to make these calculations correctly? What do I miss?

Thanks in advance.

1条回答
狗以群分
2楼-- · 2019-03-06 23:58

I've managed correct and stable image centering. Instead of calculating center of image I'm calculating UIImageView's frame's origin coordinates like this:

CGPoint newOrigin = CGPointMake((-zoomRect.origin.x * delta) + superCenter.x - (zoomRect.size.width / 2) * delta, 
                                (-zoomRect.origin.y * delta) + superCenter.y - (zoomRect.size.height / 2) * delta);

It turns out there is some difference between calculating center and origin. Anyway problem is solved. Thanks everybody.

查看更多
登录 后发表回答