2012-07-29 179 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