iphone - UIImage 旋转时质量下降

标签 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;

}

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

最佳答案

尝试

UIGraphicsBeginImageContextWithOptions(rotatedSize, NO, 2.0)

来自苹果文档:

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

参数

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

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

  • 规模 应用于位图的比例因子。如果指定值 0.0,比例因子将设置为设备主屏幕的比例因子。

再见:)

关于iphone - UIImage 旋转时质量下降,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15433897/

相关文章:

iphone - 在 iOS 上,有没有办法直接改变或绘制到 CGImage 而不是绘制到 Graphics Context 然后转换整个东西?

c++ - 使用 GLM 围绕点进行 OpenGL 旋转

iOS 8 : Game Stuck on Loading Screen

ios - 重叠透明 UIView

ios - 显示 UIAlertView 后执行操作?

基于百分比的 Javascript 内容轮换

菜单项的 JavaScript 旋转在单击后卡住

ios - 失去与 "iPhone"的连接

iphone - 状态栏点击应该将表格 View 滚动到顶部