UIImage旋转时丢失质量

问题描述:

我正在使用此代码来旋转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; 

} 

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

+0

是情况变得更糟,即使通过90/180/270度旋转?或只有当它位于那些 – Fonix 2013-03-15 13:42:14

+0

之间的天使对于任何那些学位。 – DixieFlatline 2013-03-15 13:45:15

+0

只有我能想到它的图像旋转时不与屏幕上的像素对齐,但如果质量在以直角旋转时也更糟,那么我不确定。 – Fonix 2013-03-15 13:53:29

尝试

UIGraphicsBeginImageContextWithOptions(rotatedSize, NO, 2.0) 

从苹果文档:

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

参数

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

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

  • 比例尺 适用于位图的比例因子。如果您指定的值为0.0,则缩放系数将设置为设备主屏幕的缩放系数。

再见:)

+0

谢谢..完美。 – atulkhatri 2017-05-23 09:28:02