0
votes

I need to center and scale a UIImage in a UIImageView with contentMode UIViewContentModeTopLeft by only using CGAffineTransform. I can not use contentMode UIViewContentModeCenter because i need the complete CGAffineTransform information.

So far i am using something like this where _imageView is a UIImageView and image a UIImage.

_imageView.image = image;
CGFloat scale = fmaxf(_imageView.bounds.size.width / _imageView.image.size.width, _imageView.bounds.size.height / _imageView.image.size.height);
CGAffineTransform transform = CGAffineTransformIdentity;
transform = CGAffineTransformTranslate(transform, _imageView.image.size.width * 0.5, _imageView.image.size.height * 0.5);
transform = CGAffineTransformScale(transform, scale, scale);    
_imageView.transform = transform;

The scaling is ok but the image has always some offset to the bottom right. Does anybody know how to do this without using contentMode UIViewContentModeCenter?

1

1 Answers

2
votes

Try this one:

CABasicAnimation *scaleAnim = [CABasicAnimation animationWithKeyPath:@"transform"];
scaleAnim.toValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
scaleAnim.fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)];
scaleAnim.removedOnCompletion = YES;
[_imageView.layer addAnimation:scaleAnim forKey:nil];