我想要做的是从我的相机中拍摄一张快照,将其发送到服务器,然后服务器将图像通过viewController传回给我。如果图像处于纵向模式,则图像在屏幕上显示良好,但如果图像是在横向模式下拍摄的,则图像在屏幕上呈条纹显示(因为它试图在纵向模式下显示!)。我不知道如何解决这个问题,但我猜一个解决方案是首先检查图像是否处于纵向/横向模式,如果是横向模式,则将其旋转90度,然后在屏幕上显示。那么我该怎么做呢?
发布于 2012-07-26 10:45:16
self.imageview.transform = CGAffineTransformMakeRotation(M_PI_2);
Swift 4+:
self.imageview.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi/2))
发布于 2012-07-26 10:59:10
这是完整的代码,用于旋转图像的任何程度,只需添加到适当的文件,即在.m中,如下所示,您想要使用图像处理
用于.m的
@interface UIImage (RotationMethods)
- (UIImage *)imageRotatedByDegrees:(CGFloat)degrees;
@end
@implementation UIImage (RotationMethods)
static CGFloat DegreesToRadians(CGFloat degrees) {return degrees * M_PI / 180;};
- (UIImage *)imageRotatedByDegrees:(CGFloat)degrees
{
// calculate the size of the rotated view's containing box for our drawing space
UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0,0,self.size.width, self.size.height)];
CGAffineTransform t = CGAffineTransformMakeRotation(DegreesToRadians(degrees));
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, DegreesToRadians(degrees));
// Now, draw the rotated/scaled image into the context
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 *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
@end
这是来自苹果的SquareCam示例的代码片段。
要调用上述方法,只需使用以下代码
UIImage *rotatedSquareImage = [square imageRotatedByDegrees:rotationDegrees];
这里正方形是一个UIImage
,而是一个flote
ivar,用于旋转图像
发布于 2017-04-13 20:19:16
Swift 3和Swift 4改用.pi
例如:
//rotate 90 degrees
myImageView.transform = CGAffineTransform(rotationAngle: .pi / 2)
//rotate 180 degrees
myImageView.transform = CGAffineTransform(rotationAngle: .pi)
//rotate 270 degrees
myImageView.transform = CGAffineTransform(rotationAngle: .pi * 1.5)
https://stackoverflow.com/questions/11667565
复制