2012-07-29 120 views
6

我从相机胶卷加载图像,但此图像是颠倒。所以我写了方法来旋转它。我旋转图像倒过来,但如何水平翻转它

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; 

没关系,但现在我必须水平翻转它,我不知道我该怎么做。我尝试第二天做这个。

谢谢大家帮忙

回答

21

您是否尝试过这样的:

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

imageView.transform = CGAffineTransformMakeRotation(M_PI); 

可以Concat的两个转型,一个是这样的::

您还可以通过使用转换做旋转

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

如果你想使自己的UIImage对象,而不是操纵视图和转换,我仍然建议您使用上述方法使视图根据需要绘制图像,然后将您的UIView内容转换为UIImage对象:

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

我必须转换UIImage并在CGContextRef上绘制它,所以'.transform'不可用。我尝试将UIImage添加到UIImageView,旋转它并生成'image = imageView.image',但它不起作用。 – 2012-07-29 10:33:01

+0

请查看我的编辑,了解如何将视图内容“转换”为图像。 – sergio 2012-07-29 10:35:26

+0

它正在工作,但我设置了'imageview.frame = CGRectMake(111,122,768,1024)'并且它在'0,0,768,1024'处渲染上下文。任何建议? – 2012-07-29 11:26:37