Iphone 在UITableViewCell中显示必须调整大小的图像
您好,所以我目前在CoreData模型中有一个小图像(大约100x160)作为NSData属性 我在TableView中显示所有实体。单个单元格中的UIImageView的大小仅为50x80。把图像放到这个框架里看起来有点像卵石 在我的tableViewCell中显示此图像的最佳解决方案是什么?在我的cellForRowAtIndexPath中动态调整大小?这可能会导致我的tableview变得有点滞后 在创建时调整大小并将其保存在我的coredata实体中(或者可能保存在磁盘上)Iphone 在UITableViewCell中显示必须调整大小的图像,iphone,objective-c,ios,uiimage,resize,Iphone,Objective C,Ios,Uiimage,Resize,您好,所以我目前在CoreData模型中有一个小图像(大约100x160)作为NSData属性 我在TableView中显示所有实体。单个单元格中的UIImageView的大小仅为50x80。把图像放到这个框架里看起来有点像卵石 在我的tableViewCell中显示此图像的最佳解决方案是什么?在我的cellForRowAtIndexPath中动态调整大小?这可能会导致我的tableview变得有点滞后 在创建时调整大小并将其保存在我的coredata实体中(或者可能保存在磁盘上) 谢谢大家!!
谢谢大家!!如果有不清楚的地方,请留下评论,因为您必须裁剪/调整图像大小。以下是根据所需帧裁剪图像的代码
- (void)viewDidLoad
{
[super viewDidLoad];
// do something......
UIImage *img = [UIImage imageWithData:(nsdata)]; // nsdata will be your image data as you specified.
// To crop Image
UIImage *croppedImage = [self imageByCropping:img] toRect:CGRectMake(10, 10, 50, 80)];
// To resize image
UIImage *resizedImage = [self resizeImage:img width:50 height:80];
}
裁剪图像:
- (UIImage*)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)rect
{
CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect);
UIImage *cropped = [UIImage imageWithCGImage:imageRef];
return cropped;
}
-(UIImage *)resizeImage:(UIImage *)image width:(int)width height:(int)height
{
CGImageRef imageRef = [image CGImage];
CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imageRef);
alphaInfo = kCGImageAlphaNoneSkipLast;
CGContextRef bitmap = CGBitmapContextCreate(NULL, width, height, CGImageGetBitsPerComponent(imageRef), 4 * width, CGImageGetColorSpace(imageRef), alphaInfo);
CGContextDrawImage(bitmap, CGRectMake(0, 0, width, height), imageRef);
CGImageRef ref = CGBitmapContextCreateImage(bitmap);
UIImage *result = [UIImage imageWithCGImage:ref];
return result;
}
调整图像大小:
- (UIImage*)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)rect
{
CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect);
UIImage *cropped = [UIImage imageWithCGImage:imageRef];
return cropped;
}
-(UIImage *)resizeImage:(UIImage *)image width:(int)width height:(int)height
{
CGImageRef imageRef = [image CGImage];
CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imageRef);
alphaInfo = kCGImageAlphaNoneSkipLast;
CGContextRef bitmap = CGBitmapContextCreate(NULL, width, height, CGImageGetBitsPerComponent(imageRef), 4 * width, CGImageGetColorSpace(imageRef), alphaInfo);
CGContextDrawImage(bitmap, CGRectMake(0, 0, width, height), imageRef);
CGImageRef ref = CGBitmapContextCreateImage(bitmap);
UIImage *result = [UIImage imageWithCGImage:ref];
return result;
}
您可以选择任何一种方式。我的问题不是如何调整大小,而是在滚动时是否应该调整大小。是的,您应该这样做。一旦缓存了已调整大小的图像,就可以从缓存中引用图像,而不是每次都要对其进行调整。快速滚动“我的电视”会在此列中显示错误的图像。有时它们是对的(第一次加载时),滚动通常感觉是对的,有时快速滚动在某些单元格中显示错误的图像。知道为什么会发生这种情况吗?您使用的是dequeueReusableCellWithIdentifier吗?并为每个UIImageView设置唯一的标记。什么是唯一的标签?每个单元格都有自己的标识符?