iPhone UIImageView in UIScrollView not zooming to center
I have a UIImageView
inside a UIScrollView
so I can allow zooming, the zooming works but it doesn't keep the UIImageView
centered and ends up cutting off the bottom of 开发者_开发问答the image and leaves black space on top.
This is what I have:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
scroller.bouncesZoom = YES;
scroller.clipsToBounds = YES;
float scale = image.size.width/320;
UIImage *scaled = [UIImage imageWithCGImage:[image CGImage] scale:scale orientation:UIImageOrientationUp];
imageView = [[UIImageView alloc] initWithImage:scaled];
imageView.userInteractionEnabled = YES;
[imageView setCenter:CGPointMake(160,240)];
[scroller addSubview:imageView];
scroller.contentSize = [imageView frame].size;
scroller.maximumZoomScale = 4.0;
scroller.minimumZoomScale = 1.0;
scroller.zoomScale = 1.0;
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
return imageView;
}
Any suggestions?
I think this is what you want.
If pagination is not needed then disable pagination it works fine
scrollview.pagingEnabled = NO;
Below is the code I've used in my app (adapted from the WWDC sample) Maybe you can take something out of it :)
CGSize imageSize =[image size];
CGSize boundsSize = scrollview.bounds.size;
CGRect frameToCenter = imageview.frame;
// center horizontally
if (frameToCenter.size.width < boundsSize.width)
frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2;
else
frameToCenter.origin.x = 0;
// center vertically
if (frameToCenter.size.height < boundsSize.height)
frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2;
else
frameToCenter.origin.y = 0;
imageview.frame = frameToCenter;
CGFloat xScale = boundsSize.width / imageSize.width; // the scale needed to perfectly fit the image width-wise
CGFloat yScale = boundsSize.height / imageSize.height; // the scale needed to perfectly fit the image height-wise
CGFloat minScale = MIN(xScale, yScale); // use minimum of these to allow the image to become fully visible
// on high resolution screens we have double the pixel density, so we will be seeing every pixel if we limit the
// maximum zoom scale to 0.5.
CGFloat maxScale = 1.0 / [[UIScreen mainScreen] scale];
// don't let minScale exceed maxScale. (If the image is smaller than the screen, we don't want to force it to be zoomed.)
if (minScale > maxScale) {
minScale = maxScale;
}
scrollview.contentSize=imageSize;
scrollview.maximumZoomScale=maxScale;
scrollview.minimumZoomScale=minScale;
scrollview.zoomScale=1;
精彩评论