Создание UIImage из повернутого UIImageView
У меня есть UIImageView с изображением в нем. Я повернул изображение перед отображением, установив свойство преобразования UIImageView в CGAffineTransformMakeRotation (угол), где угол - это угол в радианах.
Я хочу иметь возможность создать еще один UIImage, который соответствует повернутой версии, которую я могу видеть в моем представлении.
Я почти там, поворачивая контекст изображения, я получаю повернутое изображение:
- (UIImage *) rotatedImageFromImageView: (UIImageView *) imageView
{
UIImage *rotatedImage;
// Get image width, height of the bounding rectangle
CGRect boundingRect = [self getBoundingRectAfterRotation: imageView.bounds byAngle:angle];
// Create a graphics context the size of the bounding rectangle
UIGraphicsBeginImageContext(boundingRect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
// Rotate and translate the context
CGAffineTransform ourTransform = CGAffineTransformIdentity;
ourTransform = CGAffineTransformConcat(ourTransform, CGAffineTransformMakeRotation(angle));
CGContextConcatCTM(context, ourTransform);
// Draw the image into the context
CGContextDrawImage(context, CGRectMake(0, 0, imageView.image.size.width, imageView.image.size.height), imageView.image.CGImage);
// Get an image from the context
rotatedImage = [UIImage imageWithCGImage: CGBitmapContextCreateImage(context)];
// Clean up
UIGraphicsEndImageContext();
return rotatedImage;
}
Однако изображение не поворачивается вокруг его центра. Я пробовал все виды преобразований, соединенных с моим поворотом, чтобы заставить его вращаться вокруг центра, но безрезультатно. Мне не хватает трюка? Возможно ли это, так как я вращаю контекст, а не изображение?
Отчаянно желая сделать эту работу сейчас, поэтому любая помощь будет оценена.
Dave
EDIT: меня несколько раз спрашивали за мой код boundingRect, так что вот оно:
- (CGRect) getBoundingRectAfterRotation: (CGRect) rectangle byAngle: (CGFloat) angleOfRotation {
// Calculate the width and height of the bounding rectangle using basic trig
CGFloat newWidth = rectangle.size.width * fabs(cosf(angleOfRotation)) + rectangle.size.height * fabs(sinf(angleOfRotation));
CGFloat newHeight = rectangle.size.height * fabs(cosf(angleOfRotation)) + rectangle.size.width * fabs(sinf(angleOfRotation));
// Calculate the position of the origin
CGFloat newX = rectangle.origin.x + ((rectangle.size.width - newWidth) / 2);
CGFloat newY = rectangle.origin.y + ((rectangle.size.height - newHeight) / 2);
// Return the rectangle
return CGRectMake(newX, newY, newWidth, newHeight);
}
Ответы
Ответ 1
ОК - наконец-то я, похоже, сделал это. Любые комментарии о правильности были бы полезны... нужен перевод, поворот, масштаб и смещение от позиции выпрямления, чтобы заставить его работать. Код находится здесь:
CGAffineTransform transform = CGAffineTransformIdentity;
transform = CGAffineTransformTranslate(transform, boundingRect.size.width/2, boundingRect.size.height/2);
transform = CGAffineTransformRotate(transform, angle);
transform = CGAffineTransformScale(transform, 1.0, -1.0);
CGContextConcatCTM(context, transform);
// Draw the image into the context
CGContextDrawImage(context, CGRectMake(-imageView.image.size.width/2, -imageView.image.size.height/2, imageView.image.size.width, imageView.image.size.height), imageView.image.CGImage);
// Get an image from the context
rotatedImage = [UIImage imageWithCGImage: CGBitmapContextCreateImage(context)];