UIImageJPEGRepresentation在视网膜显示器上提供2x图像

时间:2012-03-30 18:25:56

标签: iphone objective-c ios

我有这个代码,它创建一个图像,然后添加一些效果并将其调整为largeThumbnail

UIImage *originalImage = [UIImage imageWithData:self.originalImage];
thumbnail = createLargeThumbnailFromImage(originalImage);

NSLog(@"thumbnail: %f", thumbnail.size.height);
NSData *thumbnailData = UIImageJPEGRepresentation(thumbnail, 1.0);

后来:

UIImage *image = [UIImage imageWithData:self.largeThumbnail];
NSLog(@"thumbnail 2: %f", image.size.height);

NSLog返回:

thumbnail: 289.000000
thumbnail 2: 578.000000

正如您所看到的,当它将图像从数据转换回来时,它的大小是它的2倍。任何想法为什么会这样?

大缩略图代码:

UIImage *createLargeThumbnailFromImage(UIImage *image) {
    UIImage *resizedImage;

        resizedImage = [image imageScaledToFitSize:LARGE_THUMBNAIL_SIZE];

    CGRect largeThumbnailRect = CGRectMake(0, 0, resizedImage.size.width, resizedImage.size.height);

    UIGraphicsBeginImageContextWithOptions(resizedImage.size, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();

    //Image
    CGContextTranslateCTM(context, 0, resizedImage.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextDrawImage(context, largeThumbnailRect, resizedImage.CGImage);

    //Border
    CGContextSaveGState(context);
    CGRect innerRect = rectForRectWithInset(largeThumbnailRect, 1.5);
    CGMutablePathRef borderPath = createRoundedRectForRect(innerRect, 0);
    CGContextSetStrokeColorWithColor(context, [[UIColor whiteColor] CGColor]);
    CGContextSetLineWidth(context, 3);
    CGContextAddPath(context, borderPath);
    CGContextStrokePath(context);
    CGContextRestoreGState(context);

    UIImage *thumbnail = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return thumbnail;
}

1 个答案:

答案 0 :(得分:6)

尝试替换加载第二张图像的部分:

UIImage *image = [UIImage imageWithData:self.largeThumbnail];

这一个:

UIImage *jpegImage = [UIImage imageWithData:self.largeThumbnail];
UIImage *image = [UIImage imageWithCGImage:jpegImage.CGImage scale:originalImage.scale orientation:jpegImage.imageOrientation];

这里发生的是未设置图像比例,因此您获得双倍图像尺寸。