iWizard
iWizard

Reputation: 7094

How to show in UIImage just a part of image?

I have UIImageView in which I'm showing 50x100 image.

I want to show only a part of image 50x50 (top part)?

How can I do that?

Upvotes: 8

Views: 11598

Answers (3)

malex
malex

Reputation: 10096

The very simple way to move big image inside UIImageView as follows.

Let we have the image of size (100, 400) representing 4 states of some picture one below another. We want to show the 2nd picture having offsetY = 100 in square UIImageView of size (100, 100). The solution is:

UIImageView *iView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
CGRect contentFrame = CGRectMake(0, 0.25, 1, 0.25);
iView.layer.contentsRect = contentFrame;
iView.image = [UIImage imageNamed:@"NAME"];

Here contentFrame is normalized frame relative to real UIImage size. So, "0" means that we start visible part of image from left border, "0.25" means that we have vertical offset 100, "1" means that we want to show full width of the image, and finally, "0.25" means that we want to show only 1/4 part of image in height.

Thus, in local image coordinates we show the following frame

CGRect visibleAbsoluteFrame = CGRectMake(0*100, 0.25*400, 1*100, 0.25*400)
or CGRectMake(0, 100, 100, 100);

Upvotes: 13

sergio
sergio

Reputation: 69027

You can crop the image by using CGImageCreateWithImageInRect, which is Quartz primitive working on CGImageRef, so you would have something like:

CGImageRef imageRef = CGImageCreateWithImageInRect(originalImage.CGImage, cropRect);
UIImage* outImage = [UIImage imageWithCGImage:imageRef scale:originalImage.scale orientation:originalImage.imageOrientation]]; 
CGImageRelease(imageRef);

When calculation cropRect, keep in mind that it should be given in pixels, not in points, i.e.:

float scale = originalImage.scale;
CGRect cropRect = CGRectMake(0, 0,
                         originalImage.size.width * scale, originalImage.size.height * 0.5 * scale);

where the 0.5 factor accounts for the fact that you want the top half only.

If you do not want to go low-level, you could add your image to a UIView as a background color and use the clipToBounds CALayer property to make the clipping:

myView.backgroundColor = [UIColor colorWithBackgroundPattern:myImage];
myView.layer.clipToBounds = YES;

also, set myView bounds accordingly.

Upvotes: 11

Srikar Appalaraju
Srikar Appalaraju

Reputation: 73588

I might have a solution for you. See if this works. In Interface Builder there is an option about Image content fill properties. You can set it to top-left. Follow the image in interface builder -

enter image description here

After this set the size of UIImageView to 50x50 with "clip-subviews" checked...

Upvotes: 8

Related Questions