【问题标题】:Rotate UIImage by a custom degree按自定义度数旋转 UIImage
【发布时间】:2014-05-13 13:35:37
【问题描述】:

我正在使用以下代码来实现这一点。问题是当图像旋转时,它会将图像缩放得越接近 45 度。

当图像设置为 90' 及其倍数时,图像大小没有问题。但是当度数接近 45' 及其倍数时,图像尺寸会明显缩小。我不想更改图像大小。我应该如何解决这个问题?

- (UIImage *)imageRotatedByRadians:(CGFloat)radians img:(UIImage *)img
{
    // calculate the size of the rotated view's containing box for our drawing space
    UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0,0,img.size.width, img.size.height)];
    UIView *nonrotatedViewBox = rotatedViewBox;
    CGAffineTransform t = CGAffineTransformMakeRotation(radians);
    rotatedViewBox.transform = t;
    CGSize rotatedSize = rotatedViewBox.frame.size;

    // Create the bitmap context
    UIGraphicsBeginImageContext(nonrotatedViewBox.frame.size);
    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(-img.size.width / 2, -img.size.height / 2, img.size.width, img.size.height), [img CGImage]);

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

【问题讨论】:

  • 您必须旋转图像还是可以旋转 UIImageView,这将解决您的问题。另外......您的视图尺寸是错误的,您不想以宽度和高度除以 2 来绘制图像。因为当图像旋转时,它的宽度变为(当指的是完美的正方形时)是宽度乘以 2 乘以 sqr(2)。因此,如果您的宽度和高度为 10,那么您的新宽度(45 度角)将在 14 到 15 之间......所以您的上下文是在 10x10 区域中绘制 14x14 图像
  • 您可以通过一些复杂的数学运算来使用几何获得完美的尺寸,或者您可以说| double percentRotated = (弧度% M_PI_4)/M_PI_4; double newWidth = (percentRotated == 0 ? img.size.width : img.size.width * (1 + percentRotated) );并为高度做同样的事情
  • 我需要旋转图像,因为我要保存它。我的图像是一个完美的正方形,我会尝试改变宽度。
  • 很难通过文字来解释,所以由于这个测试,取一个 100x100 的图像,在你的代码中不要旋转它并将边界设置为 100x100,然后将它旋转 45 度或 PI/4弧度,然后传入 141x141 作为宽度/高度,看看它是否正确,从那里你可能会看到我在说什么:3
  • CGFloat newsize = sqrtf((img.size.width * img.size.width)*2); ---- CGContextDrawImage(bitmap, CGRectMake(-img.size.width / 2, -img.size.height / 2, newsize, newsize), [img CGImage]); ------ 我现在这样做了,图像大小是正确的。问题是图像现在向右侧倾斜,切断了图像的一部分。有什么想法吗?

标签: ios objective-c uiimage


【解决方案1】:

您的视图尺寸错误,您不想以宽度和高度除以 2 的方式绘制图像。因为当图像旋转时,它的宽度变为(当指的是完美正方形时)是宽度乘以2 次 sqr(2)。因此,如果您的宽度和高度为 10,那么您的新宽度(以 45 度角)将在 14 到 15 之间......所以您的上下文是在 10x10 区域中绘制 14x14 图像

你可以通过一些复杂的数学运算来使用几何获得完美的尺寸,或者你可以用它说 | double percentRotated = (弧度% M_PI_4)/M_PI_4;双 newWidth = (percentRotated == 0 ? img.size.width : img.size.width * (1 + (percentRotated % 0.25)) );并为高度做同样的事情,#lazyprogrammer

【讨论】:

  • 虽然看我的回答,但 MAX 尺寸只会在 45% 时出现,所以 (1 + percentRotated) 会让他搞砸 XD,所以他应该做 percentRotated%25 意味着它以 max 为增量π/4的距离
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-29
  • 2010-11-21
  • 1970-01-01
  • 2018-08-24
  • 2023-03-28
  • 2011-01-29
相关资源
最近更新 更多