我将图像颠倒了,但如何水平翻转它?

7
我从相册中加载了一张图片,但是这张图片是倒置的。因此我编写了一个方法来将其旋转。
CGImageRef imageRef = [image CGImage];

float width = CGImageGetWidth(imageRef);
float height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
Byte *rawData = malloc(height * width * 4);
Byte bytesPerPixel = 4;
int bytesPerRow = bytesPerPixel * width;
Byte bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
int byteIndex = 0;
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);

Byte *rawData2 = malloc(height * width * 4);

for (int i = 0 ; i < width * height ; i++) {
    int index = (width * height) * 4;
    rawData2[byteIndex + 0] = rawData[index - byteIndex + 0];
    rawData2[byteIndex + 1] = rawData[index - byteIndex + 1];
    rawData2[byteIndex + 2] = rawData[index - byteIndex + 2];
    rawData2[byteIndex + 3] = rawData[index - byteIndex + 3];

    byteIndex += 4;
}

CGContextRef ctx = CGBitmapContextCreate(rawData2, CGImageGetWidth( imageRef ), CGImageGetHeight( imageRef ), 8, CGImageGetBytesPerRow( imageRef ), CGImageGetColorSpace( imageRef ),kCGImageAlphaPremultipliedLast );

imageRef = CGBitmapContextCreateImage (ctx);
image = [UIImage imageWithCGImage:imageRef];

CGContextRelease(context);

return image;

没问题,但现在我必须水平翻转它,我不知道该如何做。我已经尝试了两天。

谢谢你的帮助。

1个回答

23

你尝试过这个吗:

imageView.transform = CGAffineTransformMakeScale(-1, 1);

你也可以通过使用变换来进行旋转:

imageView.transform = CGAffineTransformMakeRotation(M_PI);

您可以将这两个变换合并成一个,像这样:

imageView.transform = CGAffineTransformRotation(CGAffineTransformMakeScale(-1, 1), M_PI);

如果你想创建自己的UIImage对象,而不是操作视图和转换,我仍然建议你使用上述方法来让视图根据你的喜好绘制图像,然后将你的UIView内容转换为一个UIImage对象:

UIGraphicsBeginImageContext(rect.size);
[imageView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage* viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

我必须将UIImage转换并绘制在CGContextRef上,因此.transform不可用。我尝试将UIImage添加到UIImageView中,旋转它并使image = imageView.image,但这并不起作用。 - Tomasz Szulc
请看我的编辑,了解如何将“视图内容”转换为图像。 - sergio
它可以工作,但我设置了imageview.frame = CGRectMake(111,122,768,1024)并且它在0,0,768,1024处渲染。有什么建议吗? - Tomasz Szulc
好的,谢谢你的帮助。我将imageView添加到subView并进行渲染。 - Tomasz Szulc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接