iPhone: how to zoom only the image from scrollview
I have this problem with ScrollView zoom. There are many articles about it but somehow I can't find proper explanation, tutorial or code snippet.
I have full screen scrollview and inside a fullscreen imageview. Inside imageview I load AspectFit images (they can be either vertical or horizontal, horizontal ones have black space above and un开发者_开发百科der). When I make zoom I zoom not only the image but also the area around (the rest of imageview). Moreover, when I rotate simulator while in zoom the image goes to top-right corner instead of being centered like at start. Few pixels even go out of the screen.
I would really like to zoom only image instead of whole imageview or at least have the image centered all the time when zoomed.
Any help welcome..
I solved the problem, it's not the best code but works good for me for now, I will probably clean it a bit later. Posting here, maybe it will help someone :)
UIImage *img = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle]
pathForResource:someImage ofType:@"jpg"]];
CGFloat scale;
if (scrollView.frame.size.width < scrollView.frame.size.height) // portrait
scale = scrollView.frame.size.width / img.size.width;
if (scrollView.frame.size.width > scrollView.frame.size.height) // landscape
scale = scrollView.frame.size.height / img.size.height;
imgView.frame = CGRectMake(scrollView.frame.origin.x, scrollView.frame.origin.y,
img.size.width*scale, img.size.height*scale);
imgView.center = CGPointMake(scrollView.frame.size.width/2, scrollView.frame.size.height/2);
[imgView setImage:img];
[scrollView setZoomScale:scale];
From the PhotoScroller example; add this to layoutSubviews:
// center the image as it becomes smaller than the size of the screen
CGSize boundsSize = self.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;
This won't help with zooming only the image but it'll keep it centered when you zoom it at least.
精彩评论