pixelbitlabs
pixelbitlabs

Reputation: 1934

How can I resize my UIImage?

Here is the code I am using to resize my UIImage, but unfortunately it isn't working:

UIImage *cellImage = [UIImage imageNamed:@"warning.png"];

CGRect cropRect = CGRectMake(0.0, 0.0, 12.0, 12.0);
CGImageRef croppedImage = CGImageCreateWithImageInRect([cellImage CGImage], cropRect);

UIImageView *myImageView = [[UIImageView alloc] initWithFrame:cropRect];
[myImageView setImage:[UIImage imageWithCGImage:croppedImage]]; 

CGImageRelease(croppedImage);

Why does this code not work?

Thanks

Upvotes: 0

Views: 695

Answers (3)

Andrew
Andrew

Reputation: 7719

Are you forgetting to add myImageView as a subview of your main view or another visible view? E.g.

[cell.contentView addSubview:myImageView];

This would explain why nothing appears.

However, CGImageCreateWithImageInRect() crops the image within the rect if your rect is smaller than the image. To resize the UIImage itself, see: The simplest way to resize an UIImage?

However, it's easiest if you just let the UIImageView handle the resizing if you don't actually need the UIImage itself resized.

UIImage *cellImage = [UIImage imageNamed:@"warning.png"];
CGRect cropRect = CGRectMake(0.0, 0.0, 12.0, 12.0);
CGImageRef croppedImage = CGImageCreateWithImageInRect([cellImage CGImage], CGRectMake(0.0f,0.0f,cellImage.size.width,cellImage.size.height));
UIImageView *myImageView = [[UIImageView alloc] initWithFrame:cropRect];
[myImageView setImage:[UIImage imageWithCGImage:croppedImage]]; 
CGImageRelease(croppedImage);
[cell.contentView addSubview:myImageView];

See:

Upvotes: 0

Gypsa
Gypsa

Reputation: 11314

HI try this:-

       UIGraphicsBeginImageContext(CGSizeMake(50,50));
       [[UIImage imageNamed:@"warning.png"] drawInRect: CGRectMake(0, 0,50,50)];
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext(); 

Upvotes: 1

Nathan Day
Nathan Day

Reputation: 6037

I don't know why that doesn't work but try using UIGraphicsBeginImageContext and UIGraphicsEndImageContext instead, UIGraphicsBeginImageContext takes a size.

Upvotes: 0

Related Questions