开发者

Display an Image that has to be resized in a UITableViewCell

Hi so i currently have a small image (about 100x160) as a NSData Attribute in my CoreData model.

i display all entities in a TableView. The UIImageView in a single Cell has only a size of 50x80. just dropping the image into this frame looks a bit pebbly.

what would be the best solution to display this image in my tableViewCell? resize it on-the-f开发者_运维百科ly in my cellForRowAtIndexPath? probably this will lead up my tableview to become a bit laggy.

resize it on create and save it in my coredata entity (or probably on disk)?

thank you! please leave a comment if something is unclear


For that you have to crop/resize the image. Following is the code to crop the image as per the required frame.

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

Crop Image:

    - (UIImage*)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)rect
    {
       CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect);
       UIImage *cropped = [UIImage imageWithCGImage:imageRef];
       return cropped;
    }

Resize Image:

    -(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;  
    }

You can go with either of ways.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜