Steve N
Steve N

Reputation: 2737

How to resize a UIImageView to fit the underlying image without moving it?

I have a UIImageView whose frame, set before the image is loaded, is always too large for the image, so when I try to round the corners, for example, nothing happens.

How can I resize the frame so it's the same size as the underlying image, while ensuring that the center point of the UIImageView does not change?

Upvotes: 8

Views: 19649

Answers (2)

drawnonward
drawnonward

Reputation: 53689

If you change the bounds of a UIView the center will not change.

CGRect bounds;

bounds.origin = CGPointZero;
bounds.size = newImage.size;

imageView.bounds = bounds;
imageView.image = newImage;

Upvotes: 13

Sujee Maniyam
Sujee Maniyam

Reputation: 1113

try something along the following lines.. not tested

CGSize imageSize = image.Size;
CGPoint oldCenter = imageView.center;

// now do some calculations to calculate the new frame size
CGRect rect = CGRectMake(0, 0, imageSize.width, imageSize.height);
imageView.frame = rect;
imageView.center = oldCenter;

Upvotes: 2

Related Questions