3

所以我有这个代码来创建一个 UIImage:

UIGraphicsBeginImageContextWithOptions(border.frame.size, YES, 0);
[border.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *thumbnailImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

此时,图像上的尺寸是正确的,80x100。

然后它运行这段代码:

NSData *fullImageData = UIImageJPEGRepresentation(image, 1.0f);

并且图像的 NSData 返回大小为 160x200 的图像 - 是应有的两倍。

很明显,原因是这条线:

UIGraphicsBeginImageContextWithOptions(border.frame.size, YES, 0);

最后的 0 是比例,因为它是 0,所以它是设备比例因子。我保持这种方式以保持清晰的图像。但是,当我将图像设置为 1 时,尽管图像保持应有的大小,但它不会以视网膜质量出现。我想要做的是将它保持在视网膜质量,但也要保持在正确的尺寸。有没有办法做到这一点?

4

2 回答 2

2

在调用 UIImageJPEGRepresentation 之前尝试调整 UIImage 的大小

- (UIImage *)resizeImage:(UIImage*)image newSize:(CGSize)newSize {
    CGRect newRect = CGRectIntegral(CGRectMake(0, 0, newSize.width, newSize.height));
    CGImageRef imageRef = image.CGImage;

    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();

    // Set the quality level to use when rescaling
    CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
    CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, newSize.height);

    CGContextConcatCTM(context, flipVertical);  
    // Draw into the context; this scales the image
    CGContextDrawImage(context, newRect, imageRef);

    // Get the resized image from the context and a UIImage
    CGImageRef newImageRef = CGBitmapContextCreateImage(context);
    UIImage *newImage = [UIImage imageWithCGImage:newImageRef];

    CGImageRelease(newImageRef);
    UIGraphicsEndImageContext();    

    return newImage;
}

if([UIScreen mainScreen].scale > 1)
    {
        thumbnailImage = [self thumbnailImage newSize:CGSizeMake(thumbnailImage.size.width/[UIScreen       mainScreen].scale, thumbnailImage.size.height/[UIScreen mainScreen].scale)];
    }
于 2012-06-11T13:02:01.217 回答
0
- (UIImage *)imageWithImage{
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;

}
于 2017-02-28T04:26:23.303 回答