【问题标题】:How to rotate an image correctly?如何正确旋转图像?
【发布时间】:2017-04-27 17:09:39
【问题描述】:

这种方法有什么问题?问题是旋转后的图像在旋转后有透明框。我怎样才能摆脱它?

@implementation UIImage (RotationMethods)

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

- (UIImage *) rotateImageByDegree:(CGFloat)degrees
{
    UIView *rotatedImageView = [[UIView alloc] initWithFrame:CGRectMake(0,0,self.size.width, self.size.height)];
    CGAffineTransform t = CGAffineTransformMakeRotation(getRadianFromDegree(degrees));
    rotatedImageView.transform = t;
    CGSize rotatedSize = rotatedImageView.frame.size;
    UIGraphicsBeginImageContextWithOptions(rotatedSize, YES, self.scale);
    CGContextRef bitmap = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);
    CGContextRotateCTM(bitmap, getRadianFromDegree(degrees));
    CGContextScaleCTM(bitmap, 1.0, -1.0);
    CGContextDrawImage(bitmap, CGRectMake(-self.size.width / 2, -self.size.height / 2, self.size.width, self.size.height), [self CGImage]);
    UIImage *rotatedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return rotatedImage;

}

@end

EDIT1

EDIT2 这是旋转动作的代码:

- (IBAction)rotateAction:(id)sender {
    self.imageView.image = [self.imageView.image rotateImageByDegree:22];
}

【问题讨论】:

  • 我猜问题出在 imageView 的 contentMode - 旋转后的图像不再适合 imageView,所以它被缩小了。
  • @matt UIGraphicsBeginImageContextWithOptions(rotatedSize, NO, self.scale); 我已更改,但没有结果还编辑了问题并添加了说明问题的图像
  • @Mr.Hedgehog 我刚刚编辑了问题
  • @matt 我已将其更改为“是”并上传了另一张图片希望它能显示我的问题
  • 确保UIImageView 的backgroundColor 设置为[UIColor clearColor]。

标签: ios objective-c uiimageview uiimage


【解决方案1】:

问题是由您未向我们展示的代码引起的。

我怎么知道?我运行了你的代码,你做显示的代码——旋转的图像和图像边界之间没有间隙:

在该屏幕截图中,主视图背景为红色,我特意将图像视图背景设置为白色,以便您可以看到旋转后的小猫图片的角与包含的图像边缘相接。

如果我们将图像视图背景设置为清除,白色会消失,我们会在红色背景上看到旋转的小猫。

因此,我们可以得出结论,您所抱怨的“收缩”是您正在做的事情,而您在问题中没有透露的事情。

【讨论】:

  • 问题是这样的:- (IBAction)rotateAction:(id)sender { self.imageView.image = [self.imageView.image rotateImageByDegree:22]; } 我需要做的就是存储实际角度并旋转初始图像:- (IBAction)rotateAction:(id)sender { self.angle += 22; self.imageView.image = [[UIImage imageNamed:@"kittens"] rotateImageByDegree:self.angle]; } 请更新答案我会接受它
猜你喜欢
  • 2019-03-29
  • 2020-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-22
相关资源
最近更新 更多