调整大小UIImage正在反转方向

时间:2015-03-17 03:58:17

标签: ios objective-c uiimage

我正在尝试调整UIImage的大小,但是当我这样做时,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;
}

2 个答案:

答案 0 :(得分:0)

我认为您遇到的问题与CGAffineTransformMake的使用有关。您可以尝试以下代码:

- (UIImage *)resizeImage:(UIImage*)image newSize:(CGSize)newSize {
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.f);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();    
    UIGraphicsEndImageContext();
    return resizedImage;
}

答案 1 :(得分:0)

UIImage有一个属性imageOrientation,可以在呈现时旋转图像。

CGImageRef是原始图像数据,因此如果要保持旋转方向,则应考虑imageOrientation。或者使用UIImage的drawInRect

UIGraphicsBeginImageContextWithOptions(newSize, NO, 0);
[image drawInRect:newRect];
ret = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();