1

以适当的比例缩放滚动视图 iOS sdk 中的图像。在滚动视图中放大图像时如何保持图像的比例。

4

1 回答 1

3
Declare following variable in .h file.

UIScrollView *scrollViewPhoto;
UIImageView *imvPhoto;

put the following code in .m file and call set image method when setting the image in imageView.


#pragma mark - set Image view
-(void)setImage:(UIImage *)imageV
{
    scrollViewPhoto.zoomScale = 1;
    scrollViewPhoto.hidden = NO;
    toolbar.hidden = NO;
    UIImage* image = imageV;
    imvPhoto.image = imageV;

    float width =  scrollViewPhoto.frame.size.width/image.size.width;
    if (image.size.width<self.view.frame.size.width) {
        width = 1;
    }

    float height = scrollViewPhoto.frame.size.height/image.size.height;
    if (image.size.height<self.view.frame.size.height) {
        height = 1;
    }

    float f = 0;

    if (width < height)
    {
        f = width;
    }
    else
    {
        f = height;
    }

    imvPhoto.frame = CGRectMake(0, 0, image.size.width*f, image.size.height*f);


    CGRect frame = scrollViewPhoto.frame;
    scrollViewPhoto.contentSize = frame.size;
    imvPhoto.center = CGPointMake(frame.size.width/2, frame.size.height/2);
}

-(void)setImageViewCenter{
    CGRect frame = scrollViewPhoto.frame;
    imvPhoto.center = CGPointMake(imvPhoto.center.x , frame.size.height/2);
}


- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{

    float width = 0;
    float height = 0;

    if (imvPhoto.frame.size.width < scrollView.frame.size.width)
    {
        width = scrollView.frame.size.width;

        if (imvPhoto.frame.size.height < scrollView.frame.size.height)
        {
            height = scrollView.frame.size.height;
        }
        else
        {
            height = scrollView.contentSize.height;
        }
    }
    else
    {
        width = scrollView.contentSize.width;

        if (imvPhoto.frame.size.height < scrollView.frame.size.height)
        {
            height = scrollView.frame.size.height;
        }
        else
        {
            height = scrollView.contentSize.height;
        }

    }

    imvPhoto.center = CGPointMake(width/2, height/2);

}


-(UIView *) viewForZoomingInScrollView:(UIScrollView *)scrollView {
return imvPhoto;
}
于 2013-10-28T09:26:50.777 回答