0

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

pixelbitlabs
  • 1,934
  • 6
  • 36
  • 65
  • 2
    What exactly is it doing/not doing? – Paul.s Nov 01 '11 at 22:52
  • possible duplicate of [How to resize the image programatically in objective-c in iphone](http://stackoverflow.com/questions/4712329/how-to-resize-the-image-programatically-in-objective-c-in-iphone) – George Stocker Nov 09 '11 at 04:15

3 Answers3

1

HI try this:-

       UIGraphicsBeginImageContext(CGSizeMake(50,50));
       [[UIImage imageNamed:@"warning.png"] drawInRect: CGRectMake(0, 0,50,50)];
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext(); 
Gypsa
  • 11,230
  • 6
  • 44
  • 82
0

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

Nathan Day
  • 5,981
  • 2
  • 24
  • 40
0

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:

Community
  • 1
  • 1
Andrew
  • 7,630
  • 3
  • 42
  • 51
  • works, but the image is in the very left hand corner of the screen, this is the image in my UITableView cell. How can I get it to align in the cell? – pixelbitlabs Nov 02 '11 at 07:53
  • instead of adding as a subview to the UIViewController's view, add it as a subview to your `UITableViewCell`'s `contentView` property. I've updated my answer to reflect this. – Andrew Nov 02 '11 at 08:15