这是一个大项目的一部分,但我的问题可以简化为: 我有一个带有ImageView和“旋转”按钮的简单视图。每当我按下按钮时,ImageView内的图像将旋转90度。从我在StackOverflow和其他网站上发现的大部分内容来看,这应该有效(请注意我的图像是方形图像,宽度和高度等于464):
- (UIImage *) getRotatedImageFromImage:(UIImage*)image:(int)rotate_index
{
UIImage *rotatedImage;
// Get image width, height of the bounding rectangle
CGRect boundingRect = CGRectMake(0, 0, image.size.width, image.size.height);
NSLog(@"width = %f, height = %f",boundingRect.size.width,boundingRect.size.height);
NSLog(@"rotate index = %d",rotate_index);
// Create a graphics context the size of the bounding rectangle
UIGraphicsBeginImageContext(boundingRect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextRotateCTM(context, rotate_index*M_PI/2);
// Draw the image into the context
[image drawInRect:boundingRect];
// Get an image from the context
rotatedImage = UIGraphicsGetImageFromCurrentImageContext();
// Clean up
UIGraphicsEndImageContext();
NSLog(@"rotatedImage size = (%f, %f)",rotatedImage.size.width,rotatedImage.size.height);
return rotatedImage;
}
- (IBAction) rotateImage
{
NSLog(@"rotate image");
rotateIndex++;
if (rotateIndex >= 4)
rotateIndex = 0;
[imageView setImage: [self getRotatedImageFromImage:imageToSubmit :rotateIndex]];
}
但由于某些原因它不起作用。我所拥有的是:当按下按钮时,图像仅在rotateIndex变为0时出现,并且图像与原始图像(预期的)相同。当rotateIndex为1,2,3时,即使打印出的rotateImage的大小正确(即464 x 464),imageView也不显示任何内容。 谁能告诉我出了什么问题? 感谢。
答案 0 :(得分:1)
//create rect
UIImageView *myImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"image.png"]];
//set point of rotation
myImageView.center = CGPointMake(100.0,100.0);
//rotate rect
myImageView.transform =CGAffineTransformMakeRotation(3.14159265/2); //rotation in radians
答案 1 :(得分:0)
我能够解决我的问题。这是我的解决方案,使用CGImageRef和[UIImage imageWithCGImage:scale:orientation:]
CGImageRef cgImageRef = CGBitmapContextCreateImage(context);
UIImageOrientation imageOrientation;
switch (rotate_index) {
case 0: imageOrientation = UIImageOrientationUp; break;
case 1: imageOrientation = UIImageOrientationLeft; break;
//2 more cases for rotate_index = 2 and 3
}
rotatedImage = [UIImage imageWithCGImage:cgImageRef scale:1.0 orientation:imageOrientation];`