2011-11-01 37 views
0

这里是我使用的调整我的UIImage的代码,但不幸的是它不工作:如何调整我的UIImage?

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); 

为什么这个代码不工作?

感谢

+2

它究竟是什么做/不这样做? –

+0

可能重复的[如何在iPhone中的Objective-C中以编程方式调整图像大小](http://stackoverflow.com/questions/4712329/how-to-resize-the-image-programatically-in-objective-c-in -iphone) –

回答

0

您是否忘记添加myImageView作为您的主视图或其他可见视图的子视图?例如。

[cell.contentView addSubview:myImageView]; 

这可以解释为什么什么都没有出现。

但是,如果您的矩形小于图像,则CGImageCreateWithImageInRect()会在矩形内裁剪出图像。要调整的UIImage本身,请参阅:The simplest way to resize an UIImage?

然而,最简单的方法,如果你只是让的UIImageView处理调整大小,如果你不真正需要的UIImage本身调整。

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]; 

参见:

+0

的作品,但图像是在屏幕的左手角落,这是我的UITableView单元格中的图像。我怎样才能让它在单元格中对齐? – pixelbitlabs

+0

,而不是将其作为子视图添加到UIViewController的视图中,而是将其作为子视图添加到您的“UITableViewCell”的contentView属性中。我已经更新了我的答案以反映这一点。 – Andrew

0

我不知道为什么不起作用,但试图利用UIGraphicsBeginImageContext和UIGraphicsEndImageContext而是UIGraphicsBeginImageContext将大小。

1

HI试试这个: -

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