gpt4 book ai didi

ios - 如何将 UIImage 和图像数据旋转 90 度

转载 作者:可可西里 更新时间:2023-11-01 05:01:32 26 4
gpt4 key购买 nike

我有一个包含图像的 UIImageView。此时用户可以单击将 UIImageView 中的图像保存到磁盘。

我想这样做,以便用户可以单击以旋转 UIImageView 并在 View 内旋转 UImage,以便在保存图像时保持新的旋转。

此刻我有

- (IBAction)rotateImage:(id)sender {

float degrees = 90; //the value in degrees
self.imagePreview.transform = CGAffineTransformMakeRotation(degrees * M_PI/180);

}

有人可以为我指出保持当前轮换的正确方向吗。

谢谢

最佳答案

我的旧应用程序中有这样的代码。但是这段代码可以简化,因为您不需要将它旋转到非 90 度角。

objective-C

@implementation UIImage (Rotation)

- (UIImage *)imageRotatedOnDegrees:(CGFloat)degrees
{
// Follow ing code can only rotate images on 90, 180, 270.. degrees.
CGFloat roundedDegrees = (CGFloat)(round(degrees / 90.0) * 90.0);
BOOL sameOrientationType = ((NSInteger)roundedDegrees) % 180 == 0;
CGFloat radians = M_PI * roundedDegrees / 180.0;
CGSize newSize = sameOrientationType ? self.size : CGSizeMake(self.size.height, self.size.width);

UIGraphicsBeginImageContext(newSize);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGImageRef cgImage = self.CGImage;
if (ctx == NULL || cgImage == NULL) {
UIGraphicsEndImageContext();
return self;
}

CGContextTranslateCTM(ctx, newSize.width / 2.0, newSize.height / 2.0);
CGContextRotateCTM(ctx, radians);
CGContextScaleCTM(ctx, 1, -1);
CGPoint origin = CGPointMake(-(self.size.width / 2.0), -(self.size.height / 2.0));
CGRect rect = CGRectZero;
rect.origin = origin;
rect.size = self.size;
CGContextDrawImage(ctx, rect, cgImage);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image ?: self;
}

@end

swift

extension UIImage {

func imageRotated(on degrees: CGFloat) -> UIImage {
// Following code can only rotate images on 90, 180, 270.. degrees.
let degrees = round(degrees / 90) * 90
let sameOrientationType = Int(degrees) % 180 == 0
let radians = CGFloat.pi * degrees / CGFloat(180)
let newSize = sameOrientationType ? size : CGSize(width: size.height, height: size.width)

UIGraphicsBeginImageContext(newSize)
defer {
UIGraphicsEndImageContext()
}

guard let ctx = UIGraphicsGetCurrentContext(), let cgImage = cgImage else {
return self
}

ctx.translateBy(x: newSize.width / 2, y: newSize.height / 2)
ctx.rotate(by: radians)
ctx.scaleBy(x: 1, y: -1)
let origin = CGPoint(x: -(size.width / 2), y: -(size.height / 2))
let rect = CGRect(origin: origin, size: size)
ctx.draw(cgImage, in: rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
return image ?? self
}

}

关于ios - 如何将 UIImage 和图像数据旋转 90 度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17909252/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com