UIImage旋转时会失去质量

时间:2013-03-15 13:38:14

标签: iphone objective-c rotation uiimage

我正在使用此代码来旋转UIImage。

CGFloat DegreesToRads(CGFloat degrees) {
   return degrees * M_PI / 180;
}

- (UIImage *)scaleAndRotateImage:(UIImage *)image forAngle: (double) angle {

    float radians=DegreesToRads(angle);
    // calculate the size of the rotated view's containing box for our drawing space
    UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0,0, image.size.width, image.size.height)];
    CGAffineTransform t = CGAffineTransformMakeRotation(radians);
    rotatedViewBox.transform = t;
    CGSize rotatedSize = rotatedViewBox.frame.size;

    // Create the bitmap context
    UIGraphicsBeginImageContext(rotatedSize);
    CGContextRef bitmap = UIGraphicsGetCurrentContext();

    // Move the origin to the middle of the image so we will rotate and scale around the center.
    CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);

    //Rotate the image context
    CGContextRotateCTM(bitmap, radians);

    // Now, draw the rotated/scaled image into the context
    CGContextScaleCTM(bitmap, 1.0, -1.0);
    CGContextDrawImage(bitmap, CGRectMake(-image.size.width/2, -image.size.height/2 , image.size.width, image.size.height), image.CGImage );

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;

}

工作正常,但旋转后图像质量更差。可能是什么原因?

1 个答案:

答案 0 :(得分:4)

尝试

UIGraphicsBeginImageContextWithOptions(rotatedSize, NO, 2.0)

来自apple文档:

void UIGraphicsBeginImageContextWithOptions(
   CGSize size,
   BOOL opaque,
   CGFloat scale
);

<强>参数

  • size 新位图上下文的大小(以磅为单位)。这表示UIGraphicsGetImageFromCurrentImageContext函数返回的图像的大小。要以像素为单位获取位图的大小,必须将width和height值乘以scale参数中的值。

  • <强>不透明 一个布尔标志,指示位图是否不透明。如果您知道位图是完全不透明的,请指定YES以忽略Alpha通道并优化位图的存储。指定NO意味着位图必须包含一个alpha通道来处理任何部分透明的像素。

  • 尺度 要应用于位图的比例因子。如果指定值0.0,则比例因子将设置为设备主屏幕的比例因子。
再见:)