Question

Is it possible to scale an image inside a UIView without changing the UIView's bounds? (That is, while still clipping the image to the UIView's bounds, even as the image scales larger than the UIView.)

I found some code on a different SO post that scales the image in a UIView:

view.transform = CGAffineTransformScale(CGAffineTransformIdentity, _scale, _scale);

However, this seems to affect the view's bounds -- making them larger -- so that the UIView's drawing now stomps over other nearby UIViews as its contents grow larger. Can I make its contents scale larger, while keeping the clipping bounds the same?

Was it helpful?

Solution

The easiest way to scale image is to use UIImageView by setting its contentMode property.

If you have to use UIView to show the image, you may try to redraw the image in UIView.

1.subclass UIView

2.draw your image in drawRect

//the followed code draw the origin size of the image

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    [_yourImage drawAtPoint:CGPointMake(0,0)];
}

//if you want to draw as much as the size of the image, you should calculate the rect that the image draws into

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    [_yourImage drawInRect:_rectToDraw];
}

- (void)setYourImage:(UIImage *)yourImage
{
    _yourImage = yourImage;

    CGFloat imageWidth = yourImage.size.width;
    CGFloat imageHeight = yourImage.size.height;

    CGFloat scaleW = imageWidth / self.bounds.size.width;
    CGFloat scaleH = imageHeight / self.bounds.size.height;

    CGFloat max = scaleW > scaleH ? scaleW : scaleH;

    _rectToDraw = CGRectMake(0, 0, imageWidth * max, imageHeight * max);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top