Alignment UIImageView with Aspect Fit - iphone

for my UIImageView I choose Aspect Fit (InterfaceBuilder) but how can I change the vertical alignment?

[EDIT - this code is a bit moldy being from 2011 and all but I incorporated #ArtOfWarefare's mods]
You can't do this w/ UIImageView. I created a simple UIView subclass MyImageView that contains a UIImageView. Code below.
// MyImageView.h
#import <UIKit/UIKit.h>
#interface MyImageView : UIView {
UIImageView *_imageView;
}
#property (nonatomic, assign) UIImage *image;
#end
and
// MyImageView.m
#import "MyImageView.h"
#implementation MyImageView
#dynamic image;
- (id)initWithCoder:(NSCoder*)coder
{
self = [super initWithCoder:coder];
if (self) {
self.clipsToBounds = YES;
_imageView = [[UIImageView alloc] initWithFrame:self.bounds];
_imageView.contentMode = UIViewContentModeScaleAspectFill;
[self addSubview:_imageView];
}
return self;
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.clipsToBounds = YES;
_imageView = [[UIImageView alloc] initWithFrame:self.bounds];
_imageView.contentMode = UIViewContentModeScaleAspectFill;
[self addSubview:_imageView];
}
return self;
}
- (id)initWithImage:(UIImage *)anImage
{
self = [self initWithFrame:CGRectZero];
if (self) {
_imageView.image = anImage;
[_imageView sizeToFit];
// initialize frame to be same size as imageView
self.frame = _imageView.bounds;
}
return self;
}
// Delete this function if you're using ARC
- (void)dealloc
{
[_imageView release];
[super dealloc];
}
- (UIImage *)image
{
return _imageView.image;
}
- (void)setImage:(UIImage *)anImage
{
_imageView.image = anImage;
[self setNeedsLayout];
}
- (void)layoutSubviews
{
if (!self.image) return;
// compute scale factor for imageView
CGFloat widthScaleFactor = CGRectGetWidth(self.bounds) / self.image.size.width;
CGFloat heightScaleFactor = CGRectGetHeight(self.bounds) / self.image.size.height;
CGFloat imageViewXOrigin = 0;
CGFloat imageViewYOrigin = 0;
CGFloat imageViewWidth;
CGFloat imageViewHeight;
// if image is narrow and tall, scale to width and align vertically to the top
if (widthScaleFactor > heightScaleFactor) {
imageViewWidth = self.image.size.width * widthScaleFactor;
imageViewHeight = self.image.size.height * widthScaleFactor;
}
// else if image is wide and short, scale to height and align horizontally centered
else {
imageViewWidth = self.image.size.width * heightScaleFactor;
imageViewHeight = self.image.size.height * heightScaleFactor;
imageViewXOrigin = - (imageViewWidth - CGRectGetWidth(self.bounds))/2;
}
_imageView.frame = CGRectMake(imageViewXOrigin,
imageViewYOrigin,
imageViewWidth,
imageViewHeight);
}
- (void)setFrame:(CGRect)frame
{
[super setFrame:frame];
[self setNeedsLayout];
}
#end

If using Storyboards this can be achieved with constraints...
Firstly a UIView with the desired final frame / constraints. Add a UIImageView to the UIView. Set the contentMode to Aspect Fill. Make the UIImageView frame be the same ratio as the image (this avoids any Storyboard warnings later). Pin the sides to the UIView using standard constraints. Pin the top OR bottom (depending where you want it aligned) to the UIView using standard constraints. Finally add an aspect ratio constraint to the UIImageView (making sure ratio as the image).

This is a bit tricky one since there is no option to set further alignment rules if you already selected a content mode (.scaleAspectFit).
But here's a workaround to this:
First need to resize your source image explicitly by calculating dimensions (if it'd be in a UIImageView with contentMode = .scaleAspectFit).
extension UIImage {
func aspectFitImage(inRect rect: CGRect) -> UIImage? {
let width = self.size.width
let height = self.size.height
let aspectWidth = rect.width / width
let aspectHeight = rect.height / height
let scaleFactor = aspectWidth > aspectHeight ? rect.size.height / height : rect.size.width / width
UIGraphicsBeginImageContextWithOptions(CGSize(width: width * scaleFactor, height: height * scaleFactor), false, 0.0)
self.draw(in: CGRect(x: 0.0, y: 0.0, width: width * scaleFactor, height: height * scaleFactor))
defer {
UIGraphicsEndImageContext()
}
return UIGraphicsGetImageFromCurrentImageContext()
}
}
Then you simply need to call this function on your original image by passing your imageView's frame and assign the result to your UIImageView.image property. Also, make sure you set your imageView's desired contentMode here (or even in the Interface Builder)!
let image = UIImage(named: "MySourceImage")
imageView.image = image?.aspectFitImage(inRect: imageView.frame)
imageView.contentMode = .left

Try setting:
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.clipsToBounds = YES;
This worked for me.

I used UIImageViewAligned for changing the alignment of image thanks to the developer
UIImageViewAligned

I know this is an old thread, but I thought I'd share what I did to easily change the clipped region from the top to the bottom of the image view in Interface Builder, in case anyone had the same problem I did. I had a UIImageView that filled the View of my ViewController, and was trying to make the top stay the same, independent of the size of the device's screen.
I applied the retina 4 form factor (Editor->Apply Retina 4 Form Factor).
I pinned the height and width.
Now, when the screen changes size, the UIImageView is actually the same size, and the view controller just clips what is off the screen. The frame origin stays at 0,0, so the bottom and right of the image are clipped, not the top.
Hope this helps.

You can do it by first scaling and then resizing.
The thing to mention here is that I was conditioned by height. I mean , I had to have the image of 34px high and no matter how width.
So , get the ratio between the actual content height and the height of the view ( 34 px ) and then scale the width too.
Here's how I did it:
CGSize size = [imageView sizeThatFits:imageView.frame.size];
CGSize actualSize;
actualSize.height = imageView.frame.size.height;
actualSize.width = size.width / (1.0 * (size.height / imageView.frame.size.height));
CGRect frame = imageView.frame;
frame.size = actualSize;
[imageView setFrame:frame];
Hope this helps.

I came up to the following solution:
Set UIImageView content mode to top: imageView.contentMode = .top
Resize image to fit UIImageView bounds
To load and resize image I use Kingfisher:
let size = imageView.bounds.size
let processor = ResizingImageProcessor(referenceSize: size, mode: .aspectFit)
imageView.kf.setImage(with: URL(string: imageUrl), options: [.processor(processor), .scaleFactor(UIScreen.main.scale)])

If you need to achieve aspectFit and get rid empty spaces
Dont forget to remove width constraint of your imageview from storyboard and enjoy
class SelfSizedImageView :UIImageView {
override func layoutSubviews() {
super.layoutSubviews()
guard let imageSize = image?.size else {
return
}
let viewBounds = bounds
let imageFactor = imageSize.width / imageSize.height
let newWidth = viewBounds.height * imageFactor
let myWidthConstraint = self.constraints.first(where: { $0.firstAttribute == .width })
myWidthConstraint?.constant = min(newWidth, UIScreen.main.bounds.width / 3)
layoutIfNeeded()
}}

I solved this by subclassing UIImageView and overriding the setImage: method. The subclass would first store it's original values for origin and size so it could use the original set size as a bounding box.
I set the content mode to UIViewContentModeAspectFit. Inside of setImage: I grabbed the image width to height ratio and then resized the image view to fit the same ratio as the image. After the resize, I adjusted my frame properties to set the image view on the same spot it was before, and then I called the super setImage:.
This results in an image view who's frame is adjusted to fit the image exactly, so aspect fit works and the image view frame properties are doing the heavy lifting in putting the image view where it should be to get the same effect.
Here's some code that I used:
First up, and I find it pretty useful in general, is a category on UIView that makes it easy to set frame properties on a view via properties like left, right, top, bottom, width, height, etc.
UIImageView+FrameAdditions
#interface UIView (FrameAdditions)
#property CGFloat left, right, top, bottom, width, height;
#property CGPoint origin;
#end
#implementation UIView (FrameAdditions)
- (CGFloat)left {
return self.frame.origin.x;
}
- (void)setLeft:(CGFloat)left {
self.frame = CGRectMake(left, self.frame.origin.y, self.frame.size.width, self.frame.size.height);
}
- (CGFloat)right {
return self.frame.origin.x + self.frame.size.width;
}
- (void)setRight:(CGFloat)right {
self.frame = CGRectMake(right - self.frame.size.width, self.frame.origin.y, self.frame.size.width, self.frame.size.height);
}
- (CGFloat)top {
return self.frame.origin.y;
}
- (void)setTop:(CGFloat)top {
self.frame = CGRectMake(self.frame.origin.x, top, self.frame.size.width, self.frame.size.height);
}
- (CGFloat)bottom {
return self.frame.origin.y + self.frame.size.height;
}
- (void)setBottom:(CGFloat)bottom {
self.frame = CGRectMake(self.frame.origin.x, bottom - self.frame.size.height, self.frame.size.width, self.frame.size.height);
}
- (CGFloat)width {
return self.frame.size.width;
}
- (void)setWidth:(CGFloat)width {
self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, width, self.frame.size.height);
}
- (CGFloat)height {
return self.frame.size.height;
}
- (void)setHeight:(CGFloat)height {
self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, height);
}
- (CGPoint)origin {
return self.frame.origin;
}
- (void)setOrigin:(CGPoint)origin {
self.frame = CGRectMake(origin.x, origin.y, self.frame.size.width, self.frame.size.height);
}
#end
This is the subclass of UIImageView. It is not fully tested, but should get the idea across. This could be expanded to set your own new modes for alignment.
BottomCenteredImageView
#interface BottomCenteredImageView : UIImageView
#end
#interface BottomCenteredImageView() {
CGFloat originalLeft;
CGFloat originalBottom;
CGFloat originalHeight;
CGFloat originalWidth;
}
#end
#implementation BottomCenteredImageView
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if(self) {
[self initialize];
}
return self;
}
- (void)awakeFromNib {
[self initialize];
}
- (void)initialize {
originalLeft = self.frame.origin.x;
originalHeight = CGRectGetHeight(self.frame);
originalWidth = CGRectGetWidth(self.frame);
originalBottom = self.frame.origin.y + originalHeight;
}
- (void)setImage:(UIImage *)image {
if(image) {
self.width = originalWidth;
self.height = originalHeight;
self.left = originalLeft;
self.bottom = originalBottom;
float myWidthToHeightRatio = originalWidth/originalHeight;
float imageWidthToHeightRatio = image.size.width/image.size.height;
if(myWidthToHeightRatio >= imageWidthToHeightRatio) {
// Calculate my new width
CGFloat newWidth = self.height * imageWidthToHeightRatio;
self.width = newWidth;
self.left = originalLeft + (originalWidth - self.width)/2;
self.bottom = originalBottom;
} else {
// Calculate my new height
CGFloat newHeight = self.width / imageWidthToHeightRatio;
self.height = newHeight;
self.bottom = originalBottom;
}
self.contentMode = UIViewContentModeScaleAspectFit;
[super setImage:image];
} else {
[super setImage:image];
}
}
#end

Credit to #michael-platt
Key Points
imageView.contentMode = .scaleAspectFit
let width = Layout.height * image.size.width / image.size.height
imageView.widthAnchor.constraint(equalToConstant: width).isActive = true
Code:
func setupImageView(for image: UIImage) {
let imageView = UIImageView()
imageView.backgroundColor = .orange
//Content mode
imageView.contentMode = .scaleAspectFill
view.addSubview(imageView)
//Constraints
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
imageView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
//Feel free to set the height to any value
imageView.heightAnchor.constraint(equalToConstant: 150).isActive = true
//ImageView width calculation
let width = Layout.height * image.size.width / image.size.height
imageView.widthAnchor.constraint(equalToConstant: width).isActive = true
}

To align a scale-to-fit image use auto layout. Example right aligned image after scale-to-fit in UIImageView:
Create UIImageView that holds the image
Add auto constraints for right, top, bottom, width
Set the image:
myUIImageView.contentMode = .ScaleAspectFit
myUIImageView.translatesAutoresizingMaskIntoConstraints = false
myUIImageView.image = UIImage(named:"pizza.png")
Your aspect fit scaled image is now right aligned in the UIImageView
+----------------------------------+
| [IMAGE]|
+----------------------------------+
Change the constraints to align differently within the imageview.

Related

Resize UIImage and change the size of UIImageView

I have this UIImageView and I have the values of its max height and max width. What I want to achieve is that I want to take the image (with any aspect ratio and any resolution) and I want it to fit in the borders, so the picture does not exceed them, but it can shrink them as it wants. (marked red in the picture):
Right now the image fits the necessary size properly, but I have 2 worries:
1. The UIImageView is not equal the size of the resized image, thus leaving red background (and I don't want that)
2. If the image is smaller that the height of my UIImageView it is not resized to be smaller, it stays the same height.
Here's my code and I know its wrong:
UIImage *actualImage = [attachmentsArray lastObject];
UIImageView *attachmentImageNew = [[UIImageView alloc] initWithFrame:CGRectMake(5.5, 6.5, 245, 134)];
attachmentImageNew.image = actualImage;
attachmentImageNew.backgroundColor = [UIColor redColor];
attachmentImageNew.contentMode = UIViewContentModeScaleAspectFit;
So how do I dynamically change the size not only of the UIImageView.image, but of the whole UIImageView, thus making its size totally adjustable to its content. Any help would be much appreciated, thanks!
When you get the width and height of a resized image Get width of a resized image after UIViewContentModeScaleAspectFit, you can resize your imageView:
imageView.frame = CGRectMake(0, 0, resizedWidth, resizedHeight);
imageView.center = imageView.superview.center;
I haven't checked if it works, but I think all should be OK
- (UIImage *)image:(UIImage*)originalImage scaledToSize:(CGSize)size
{
//avoid redundant drawing
if (CGSizeEqualToSize(originalImage.size, size))
{
return originalImage;
}
//create drawing context
UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);
//draw
[originalImage drawInRect:CGRectMake(0.0f, 0.0f, size.width, size.height)];
//capture resultant image
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//return image
return image;
}
This is the Swift equivalent for Rajneesh071's answer, using extensions
UIImage {
func scaleToSize(aSize :CGSize) -> UIImage {
if (CGSizeEqualToSize(self.size, aSize)) {
return self
}
UIGraphicsBeginImageContextWithOptions(aSize, false, 0.0)
self.drawInRect(CGRectMake(0.0, 0.0, aSize.width, aSize.height))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
Usage:
let image = UIImage(named: "Icon")
item.icon = image?.scaleToSize(CGSize(width: 30.0, height: 30.0))
Use the category below and then apply border from Quartz into your image:
[yourimage.layer setBorderColor:[[UIColor whiteColor] CGColor]];
[yourimage.layer setBorderWidth:2];
The category:
UIImage+AutoScaleResize.h
#import <Foundation/Foundation.h>
#interface UIImage (AutoScaleResize)
- (UIImage *)imageByScalingAndCroppingForSize:(CGSize)targetSize;
#end
UIImage+AutoScaleResize.m
#import "UIImage+AutoScaleResize.h"
#implementation UIImage (AutoScaleResize)
- (UIImage *)imageByScalingAndCroppingForSize:(CGSize)targetSize
{
UIImage *sourceImage = self;
UIImage *newImage = nil;
CGSize imageSize = sourceImage.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
CGFloat targetWidth = targetSize.width;
CGFloat targetHeight = targetSize.height;
CGFloat scaleFactor = 0.0;
CGFloat scaledWidth = targetWidth;
CGFloat scaledHeight = targetHeight;
CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
if (CGSizeEqualToSize(imageSize, targetSize) == NO)
{
CGFloat widthFactor = targetWidth / width;
CGFloat heightFactor = targetHeight / height;
if (widthFactor > heightFactor)
{
scaleFactor = widthFactor; // scale to fit height
}
else
{
scaleFactor = heightFactor; // scale to fit width
}
scaledWidth = width * scaleFactor;
scaledHeight = height * scaleFactor;
// center the image
if (widthFactor > heightFactor)
{
thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
}
else
{
if (widthFactor < heightFactor)
{
thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
}
}
}
UIGraphicsBeginImageContext(targetSize); // this will crop
CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width = scaledWidth;
thumbnailRect.size.height = scaledHeight;
[sourceImage drawInRect:thumbnailRect];
newImage = UIGraphicsGetImageFromCurrentImageContext();
if(newImage == nil)
{
NSLog(#"could not scale image");
}
//pop the context to get back to the default
UIGraphicsEndImageContext();
return newImage;
}
#end
If you have the size of the image, why don't you set the frame.size of the image view to be of this size?
EDIT----
Ok, so seeing your comment I propose this:
UIImageView *imageView;
//so let's say you're image view size is set to the maximum size you want
CGFloat maxWidth = imageView.frame.size.width;
CGFloat maxHeight = imageView.frame.size.height;
CGFloat viewRatio = maxWidth / maxHeight;
CGFloat imageRatio = image.size.height / image.size.width;
if (imageRatio > viewRatio) {
CGFloat imageViewHeight = round(maxWidth * imageRatio);
imageView.frame = CGRectMake(0, ceil((self.bounds.size.height - imageViewHeight) / 2.f), maxWidth, imageViewHeight);
}
else if (imageRatio < viewRatio) {
CGFloat imageViewWidth = roundf(maxHeight / imageRatio);
imageView.frame = CGRectMake(ceil((maxWidth - imageViewWidth) / 2.f), 0, imageViewWidth, maxHeight);
} else {
//your image view is already at the good size
}
This code will resize your image view to its image ratio, and also position the image view to the same centre as your "default" position.
PS: I hope you're setting imageView.layer.shouldRasterise = YES
and imageView.layer.rasterizationScale = [UIScreen mainScreen].scale;
if you're using CALayer shadow effect ;) It will greatly improve the performance of your UI.
I think what you want is a different content mode. Try using UIViewContentModeScaleToFill. This will scale the content to fit the size of ur UIImageView by changing the aspect ratio of the content if necessary.
Have a look to the content mode section on the official doc to get a better idea of the different content mode available (it is illustrated with images).
if([[SDWebImageManager sharedManager] diskImageExistsForURL:[NSURL URLWithString:#"URL STRING1"]])
{
NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:[NSURL URLWithString:#"URL STRING1"]];
UIImage *tempImage=[self imageWithImage:[[SDImageCache sharedImageCache] imageFromDiskCacheForKey:key] scaledToWidth:cell.imgview.bounds.size.width];
cell.imgview.image=tempImage;
}
else
{
[cell.imgview sd_setImageWithURL:[NSURL URLWithString:#"URL STRING1"] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL)
{
UIImage *tempImage=[self imageWithImage:image scaledToWidth:cell.imgview.bounds.size.width];
cell.imgview.image=tempImage;
// [tableView beginUpdates];
// [tableView endUpdates];
}];
}

crop a zoomed image in ImageView inside scrollView

I already do Lot of efforts from my Side. finally I need help. thanks
Goal :
1) How I fit imageView inside ScrollView
2) How I crop a zoomed Image in inside scrollView.
I have a imageView inside Scroll View. I wants crop image after zoomed which is display inside scrollview boundary. I cropped image already but it not exactly same which i wants.
Here I set backgroundColor Black to my scrollView. And when I place imageView inside it, it's not fit.
after zoom image inside scroll view is
and after crop image is
and my code is here :
- (void)viewDidLoad
{
[super viewDidLoad];
CGRect frame1 = CGRectMake(50,50,200,200);
CGRect frame2 = CGRectMake(50,50,200,200);
imageView1=[[UIImageView alloc]initWithFrame:frame1];
imageView1.image= [UIImage imageNamed:#"back.jpeg"];
imageView1.backgroundColor=[UIColor brownColor];
imageView1.contentMode = UIViewContentModeScaleAspectFit;
scroll=[[UIScrollView alloc]initWithFrame:frame2];
scroll.backgroundColor=[UIColor blackColor];
[scroll addSubview:imageView1];
scroll.delegate=self;
[self.view addSubview:scroll];
[self setContentSizeForScrollView];
self.imageView1.userInteractionEnabled = YES;
}
setting scroll view contentSize
-(void)setContentSizeForScrollView
{
// scroll.contentSize = CGSizeMake(imageView1.frame.size.width,imageView1.frame.size.height);
scroll.contentSize = CGSizeMake(200, 200);
scroll.minimumZoomScale = .50;
scroll.maximumZoomScale = 1.5;
}
and my crop logic is
-(IBAction)cropButtonClicked
{
//Calculate the required area from the scrollview
CGRect rect = CGRectMake(50, 50, 200,200);
UIImage *image = [self imageByCropping:imageView1.image toRect:rect];
imageView1.image=image;
imageView1.contentMode = UIViewContentModeScaleAspectFit;
}
And this method crop image :
- (UIImage*)imageByCropping:(UIImage *)myImage toRect:(CGRect)cropToArea{
CGImageRef cropImageRef = CGImageCreateWithImageInRect(myImage.CGImage, cropToArea);
UIImage* cropped = [UIImage imageWithCGImage:cropImageRef];
CGImageRelease(cropImageRef);
return cropped;
}
Answer of my own Question : After many efforts i found the answer of both of my questions.
and it work good for me. I share here, may be it help someone. :)
1) Fit image View inside Scroll View. I use this link
- (void)centerScrollViewContents {
CGSize boundsSize = scroll.bounds.size;
CGRect contentsFrame = self.imageView1.frame;
if (contentsFrame.size.width < boundsSize.width) {
contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0f;
}
else {
contentsFrame.origin.x = 0.0f;
}
if (contentsFrame.size.height < boundsSize.height) {
contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0f;
}
else {
contentsFrame.origin.y = 0.0f;
}
self.imageView1.frame = contentsFrame;
}
2) Crop a zoomed Image in inside scrollView. I use this link
UIGraphicsBeginImageContext(CGSizeMake(200, 200));
[scroll.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *fullScreenshot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
imageView1.contentMode = UIViewContentModeScaleAspectFill;
UIImageWriteToSavedPhotosAlbum(fullScreenshot, nil, nil, nil);
return fullScreenshot;
I had a similar problem recently, I got the solution using the relative idea ( Xa,b = Xa,c - Xb,c )
-(IBAction)crop:(id)sender{
// F = frame
// i = image
// iv = imageview
// sv = self.view
// of = offset
//Frame Image in imageView coordinates
CGRect Fi_iv = [self frameForImage:self.image inImageViewAspectFit:self.imageView];
//Frame ImageView in self.view coordinates
CGRect Fiv_sv = self.imageView.frame;
//Frame Image in self.view coordinates
CGRect Fi_sv = CGRectMake(Fi_iv.origin.x + Fiv_sv.origin.x
,Fi_iv.origin.y + Fiv_sv.origin.y,
Fi_iv.size.width, Fi_iv.size.height);
//ScrollView offset
CGPoint offset = self.scrollView.contentOffset;
//Frame Image in offset coordinates
CGRect Fi_of = CGRectMake(Fi_sv.origin.x - offset.x,
Fi_sv.origin.y - offset.y,
Fi_sv.size.width,
Fi_sv.size.height);
CGFloat scale = self.imageView.image.size.width/Fi_of.size.width;
//the crop frame in image offset coordinates
CGRect Fcrop_iof = CGRectMake((self.cropView.frame.origin.x - Fi_of.origin.x)*scale,
(self.cropView.frame.origin.y - Fi_of.origin.y)*scale,
self.cropView.frame.size.width*scale,
self.cropView.frame.size.height*scale);
UIImage *image = [self image:self.imageView.image cropRect:Fcrop_iof];
// Use this crop image...
You can crop the image using:
//Use this code to crop when you have the right frame
-(UIImage*)image:(UIImage *)image cropRect:(CGRect)frame
{
// Create a new UIImage
CGImageRef imageRef = CGImageCreateWithImageInRect(image.CGImage, frame);
UIImage *croppedImage = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return croppedImage;
}
Since you are using the ImageView in Aspect Fit, you need to calculate the image frame inside the imageView
-(CGRect)frameForImage:(UIImage*)image inImageViewAspectFit:(UIImageView*)imageView
{
float imageRatio = image.size.width / image.size.height;
float viewRatio = imageView.frame.size.width / imageView.frame.size.height;
if(imageRatio < viewRatio)
{
float scale = imageView.frame.size.height / image.size.height;
float width = scale * image.size.width;
float topLeftX = (imageView.frame.size.width - width) * 0.5;
return CGRectMake(topLeftX, 0, width, imageView.frame.size.height);
}
else
{
float scale = imageView.frame.size.width / image.size.width;
float height = scale * image.size.height;
float topLeftY = (imageView.frame.size.height - height) * 0.5;
return CGRectMake(0, topLeftY, imageView.frame.size.width, height);
}
}
I hope this code can work for you as it worked for me.
Best,
Rafael.

UIScrollView Zooming Crashes App with Exc_Bad_Access

I am getting a Exc_Bad_Access error in main when I try to scroll my UIScrollView. This program is simple. I have A UIViewController added in AppDelegate. Then, here is the code in the ViewController. This works fine for scrolling but as soon as I add tmpScrollView.delegate = self. The program won't scroll or zoom and gives me the Exc_Bad_Access error when I try to zoom.
#interface MainViewController : UIViewController &ltUIScrollViewDelegate>
#property (nonatomic,retain) UIScrollView *tmpScrollView;
#property (nonatomic,retain) UIView *containerView;
#end
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
tmpScrollView = [[UIScrollView alloc] initWithFrame:self.view.frame];
tmpScrollView.delegate = self;
[self.view addSubview:tmpScrollView];
// Set up the container view to hold our custom view hierarchy
CGSize containerSize = CGSizeMake(640.0f, 640.0f);
self.containerView = [[UIView alloc] initWithFrame:(CGRect){.origin=CGPointMake(0.0f, 0.0f), .size=containerSize}];
[self.tmpScrollView addSubview:self.containerView];
// Set up custom view hierarchy
UIView *redView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 640.0f, 80.0f)];
redView.backgroundColor = [UIColor redColor];
[self.containerView addSubview:redView];
UIView *blueView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 560.0f, 640.0f, 80.0f)];
blueView.backgroundColor = [UIColor blueColor];
[self.containerView addSubview:blueView];
UIView *greenView = [[UIView alloc] initWithFrame:CGRectMake(160.0f, 160.0f, 320.0f, 320.0f)];
greenView.backgroundColor = [UIColor greenColor];
[self.containerView addSubview:greenView];
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"slow.png"]];
imageView.center = CGPointMake(320.0f, 320.0f);
[self.containerView addSubview:imageView];
//Tell the scroll view the size of the contents
self.tmpScrollView.contentSize = containerSize;
}
-(void)viewWillAppear:(BOOL)animated
{
NSLog(#"Will Appear");
[super viewWillAppear:animated];
// Set up the minimum & maximum zoom scales
CGRect scrollViewFrame = self.tmpScrollView.frame;
CGFloat scaleWidth = scrollViewFrame.size.width / self.tmpScrollView.contentSize.width;
CGFloat scaleHeight = scrollViewFrame.size.height / self.tmpScrollView.contentSize.height;
CGFloat minScale = MIN(scaleWidth, scaleHeight);
self.tmpScrollView.minimumZoomScale = minScale;
self.tmpScrollView.maximumZoomScale = 1.0f;
self.tmpScrollView.zoomScale = minScale;
//***** Here is the line for setting the delegate
self.tmpScrollView.delegate = self;
[self centerScrollViewContents];
}
-(void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale
{
NSLog(#"End Zoom");
}
-(UIView*)viewForZoomingInScrollView:(UIScrollView *)scrollView {
// Return the view that we want to zoom
return self.containerView;
}
-(void)scrollViewDidZoom:(UIScrollView *)scrollView {
// The scroll view has zoomed, so we need to re-center the contents
[self centerScrollViewContents];
}
#end
Thanks for any help. This has been driving me crazy for a day now...
Edit: Adding centerScrollViewContens too:
- (void)centerScrollViewContents {
CGSize boundsSize = self.tmpScrollView.bounds.size;
CGRect contentsFrame = self.containerView.frame;
if (contentsFrame.size.width < boundsSize.width) {
contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0f;
} else {
contentsFrame.origin.x = 0.0f;
}
if (contentsFrame.size.height < boundsSize.height) {
contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0f;
} else {
contentsFrame.origin.y = 0.0f;
}
self.containerView.frame = contentsFrame;
}
Whatever Code you have provided is working fine on my end.May be there could be some sort of problem in your "centerScrollViewContents" method.Can you post the code for this method also???
You need to work out the minimum zoom scale for the scroll view. A zoom scale of one means that the content is displayed at normal size. A zoom scale below one shows the content zoomed out, while a zoom scale of greater than one shows the content zoomed in. To get the minimum zoom scale, you calculate how far you’d need to zoom out so that the image fits snugly in your scroll view’s bounds based on its width. Then you do the same based upon the image’s height. The minimum of those two resulting zoom scales will be the scroll view’s minimum zoom scale. That gives you a zoom scale where you can see the entire image when fully zoomed out.
Swift:
let scrollViewFrame = scrollView.frame
let scaleWidth = scrollViewFrame.size.width / scrollView.contentSize.width
let scaleHeight = scrollViewFrame.size.height / scrollView.contentSize.height
let minScale = min(scaleWidth, scaleHeight);
scrollView.minimumZoomScale = minScale;
Objective-C
CGFloat scrollViewFrame = scrollView.frame
CGFloat scaleWidth = scrollViewFrame.size.width / scrollView.contentSize.width
CGFloat scaleHeight = scrollViewFrame.size.height / scrollView.contentSize.height
CGFloat minScale = min(scaleWidth, scaleHeight);
scrollView.minimumZoomScale = minScale;
From other projects and personal experience doing heavy GPU on the iOS (endless scroll, maximum bitmap size, etc), I've noticed that each device has it's own threshold. For past projects, I've also hardcoded the below values as the minimumZoomScale to prevent the crashes:
scale :
{
iPad : {
min : 0.8
, max : 1.6
}
, iPhone : {
min : 0.25
, max : 1.6
}
, iPhone6 : {
min : 0.3333
, max : 1.6
}
, iPhoneResizable: {
min : 1
, max : 1.6
}
}
Great tutorial for beginners: http://www.raywenderlich.com/76436/use-uiscrollview-scroll-zoom-content-swift

How to center image in a uiimageview/uiscrollview (pre and post zooming)

I am trying to center an image (with respect to the iphone screen) such that when the view is loaded the image is center width/height... In my case my view is loaded at pixel points 0,0 of the image itself and if I zoom out the image appears in the top left corner as opposed to mid-center of the screen/view. Here is what I have so far:
UIImage *image = [UIImage imageNamed: #"t.bmp"];
self.view.backgroundColor = [UIColor blackColor];
self.mi.frame = CGRectMake(0, 0, image.size.width, image.size.height);
self.mi.contentMode = (UIViewContentModeCenter);
self.mi.backgroundColor = [UIColor blackColor];
[self.mi setImage:image];
/* Draw a line here!!
UIGraphicsBeginImageContext(self.mi.frame.size);
[self.mi.image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
CGContextSetLineWidth(context, 20.0);
CGContextBeginPath(context);
CGContextMoveToPoint(context, 0,0);
CGContextAddLineToPoint(context, 200, 200);
CGContextMoveToPoint(context, 200,0);
CGContextAddLineToPoint(context, 0, 200);
CGContextStrokePath(context);
self.mi.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
*/
self.expimg.maximumZoomScale = 2.0;
self.expimg.minimumZoomScale = 0.1;
self.expimg.clipsToBounds = YES;
self.expimg.delegate = self;
[self.expimg setContentSize:self.mi.frame.size];
[self.expimg addSubview: self.mi];
[self.view addSubview: self.expimg];
Thanks!
Edit: mi is a UIImageView and expimg is a UIScrollView (used interface builder). Also, viewForZoomingInScrollView is defined.
You should be able to do this by adjusting the position and size of the image and scroll view on initial load, and as zoom levels change. Make a method that is called on viewDidLoad, and again on the UIScrollViewDelegate method scrollViewDidZoom:.
Something like this should work (where imageView and scrollView are class attributes):
- (void)centerImage {
CGSize screenSize = CGSizeMake(320, 480);
CGSize imageSize = imageView.frame.size;
imageSize.width = imageSize.width * scrollView.zoomScale;
imageSize.height = imageSize.height * scrollView.zoomScale;
CGSize scrollSize = scrollView.frame.size;
CGFloat centerX;
CGFloat centerY;
CGFloat left;
CGFloat top;
if (imageSize.width > screenSize.width) {
scrollSize.width = imageSize.width;
centerX = imageSize.width/2;
left = 0;
} else {
scrollSize.width = screenSize.width;
centerX = screenSize.width/2;
left = centerX - imageSize.width/2;
}
if (imageSize.height > screenSize.height) {
scrollSize.height = imageSize.height;
centerY = imageSize.height/2;
top = 0;
} else {
scrollSize.height = screenSize.height;
centerY = screenSize.width/2;
top = centerY - imageSize.height/2;
}
CGRect scrollFrame = scrollView.frame;
scrollFrame.size = scrollSize;
scrollView.frame = scrollFrame;
CGRect imageFrame = imageView.frame;
imageFrame.origin = CGPointMake(left, top);
scrollView.contentOffset = CGPointMake(centerX-(imageSize.width/2), centerY-(imageSize.height/2));
}
I have not tested this, so some of my math could be wrong. Either way, it will hopefully give you a good idea of what to do.
Step 1: You create an image view property then init it at viewDidLoad and add to scrollView:
self.pictureImage = [[UIImageView alloc]initWithImage:self.picture];
[_scrollView addSubview:_pictureImage];
self.pictureImage.alpha = 0;
_scrollView.delegate = self;
Step 2: Create adjustZoomScale function to get minimum scale
- (CGFloat)adjustZoomScale{
CGFloat scale = self.scrollView.bounds.size.width / self.pictureImage.bounds.size.width;
CGFloat h = scale * self.pictureImage.bounds.size.height;
if (h > self.scrollView.bounds.size.height) {
scale = self.scrollView.bounds.size.height / self.pictureImage.bounds.size.height;
}
return scale;
}
Step 3: Because frame of scroll view will be updated at viewDidAppear so we need to adjust zoom scale here. And set alpha to make image appear smoother:
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear: animated];
_scrollView.maximumZoomScale = 1.0;
_scrollView.minimumZoomScale = [self adjustZoomScale];
[_scrollView setZoomScale:_scrollView.minimumZoomScale];
self.pictureImage.alpha = 1;
}
Step 4: Implement viewForZoomingInScrollView (scroll delegate method) and return image view
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
return self.pictureImage;
}
Step 5: Implement scrollViewDidZoom (scroll delegate method) and adjust point for image view
- (void)scrollViewDidZoom: (UIScrollView*) scrollView {
CGSize boundsSize = scrollView.bounds.size;
CGRect contentsFrame = _pictureImage.frame;
if (contentsFrame.size.width < boundsSize.width) {
contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0;
} else {
contentsFrame.origin.x = 0.0;
}
if (contentsFrame.size.height < boundsSize.height) {
contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0;
} else {
contentsFrame.origin.y = 0.0;
}
_pictureImage.frame = contentsFrame;
}
Thank shawhu at this post for point adjusting for image view while zooming
[scrollView zoomToRect:CGRectMake(x, y, width, height) animated:YES]; will work for you...
Where rect should have those center coordinates as origin.

UIScrollView height change

I have a UITableView containing a list of maps. When an item is selected a new sub view is added to the main window and the map is shown. In my view controller for the map view the following method gets called each time it's displayed:
- (void)showMap {
UIImageView *tempImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:mapImage]];
float imageHeight = tempImageView.image.size.height;
float targetHeight = scrollView.frame.size.height - mapNavigationController.navigationBar.frame.size.height;
scrollView.contentSize = tempImageView.image.size;
scrollView.maximumZoomScale = 1.0;
scrollView.minimumZoomScale = targetHeight / imageHeight;
scrollView.clipsToBounds = YES;
self.imageView = tempImageView;
[tempImageView release];
[scrollView addSubview:imageView];
scrollView.zoomScale = scrollView.minimumZoomScale;}
A new UIImageView is added each time to the UIScrollView and when the view disappears the UIImageView is removed. The zoomScale is calculated so that the image fits according to the aspect ratio.
Now to my problem the first time an item is clicked everything works fine and the map image fills the full height of the UIScrollView, but the next time an item is clicked the height of the UIScrollView is smaller. I also should note that the main window contains a tab bar.
So now to my questions:
How can the UIScrollView change it's size?
And is there any other dynamic way to retrieve the targetHeight?
Thanks in advance!
I was having a similar problem. It turns out the issue was that I was subclassing UIScrollView for the main view of my UIViewController, and the UIViewController had its own ideas about the correct size of the scroll view.
I fixed it by making the main view subclass UIView rather than UIScrollView, then adding a UIScrollView* content_view to the view, and adding my subviews to content_view rather than to self.
Not sure if this helps you or not, however...
Ok, i managed to found a solution my self, maybe not the best but it's dynamic and it works.
But i still don't understand why the height of UIScrollView would change. If someone know why please comment.
NSInteger scrollViewHeight = 0;
- (void)showMap {
if (scrollViewHeight == 0) {
scrollViewHeight = scrollView.frame.size.height;
} else {
scrollView.frame.size.height = scrollViewHeight;
}
UIImageView *tempImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:mapImage]];
float imageWidth = tempImageView.image.size.width;
float imageHeight = tempImageView.image.size.height;
float targetWidth = scrollView.frame.size.width;
float targetHeight = scrollViewHeight - mapNavigationController.navigationBar.frame.size.height;
float scale = targetHeight / imageHeight;
if (scale * imageWidth < targetWidth) {
scale = targetWidth / imageWidth;
}
scrollView.contentSize = tempImageView.image.size;
scrollView.maximumZoomScale = 1.0;
scrollView.minimumZoomScale = scale;
scrollView.clipsToBounds = YES;
self.imageView = tempImageView;
[tempImageView release];
[scrollView addSubview:imageView];
scrollView.zoomScale = scale;}
}