How do I pan the image inside a UIImageView?

前端 未结 2 924
情书的邮戳
情书的邮戳 2020-11-29 23:07

I have a UIImageView that is displaying an image that is wider and taller than the UIImageView is. I would like to pan the image within the view us

2条回答
  •  抹茶落季
    2020-11-29 23:47

    Brad Larson pointed me down the right road with his suggestion to put the UIImageView inside a UIScrollView.

    In the end I put the UIImageView inside of a UIScrollView, and set the scrollView's contentSize and the imageView's bounds to be the same size as the image in the UIImage:

    UIImage* image = imageView.image;
    imageView.bounds = CGRectMake(0, 0, image.size.width, image.size.height);
    scrollView.contentSize = image.size;
    

    Then, I can animate the scrollView's contentOffset to achieve a nice panning effect:

    [UIView beginAnimations:@"pan" context:nil];
    [UIView setAnimationDuration:animationDuration];
    scrollView.contentOffset = newRect.origin;
    [UIView commitAnimations];
    

    In my particular case, I'm panning to a random space in the image. In order to find a proper rect to pan to and a proper duration to get a nice constant speed, I use the following:

    UIImage* image = imageView.image;
    
    float xNewOrigin = [TCBRandom randomIntLessThan:image.size.width - scrollView.bounds.size.width];
    float yNewOrigin = [TCBRandom randomIntLessThan:image.size.height - scrollView.bounds.size.height];
    
    CGRect oldRect = scrollView.bounds;
    CGRect newRect = CGRectMake(
        xNewOrigin,
        yNewOrigin, 
        scrollView.bounds.size.width,
        scrollView.bounds.size.height);
    
    float xDistance = fabs(xNewOrigin - oldRect.origin.x);
    float yDistance = fabs(yNewOrigin - oldRect.origin.y);
    float hDistance = sqrtf(powf(xDistance, 2) + powf(yDistance, 2));
    float hDistanceInPixels = hDistance;
    
    float animationDuration = hDistanceInPixels / speedInPixelsPerSecond;
    

    I'm using a speedInPixelsPerSecond of 10.0f, but other applications might want to use a different value.

提交回复
热议问题