2011-11-08 29 views
0

這是一個大項目的一部分,但我的問題可以簡化爲: 我有一個簡單的視圖與ImageView和「旋轉」按鈕。每當我按下按鈕,ImageView內的圖像將旋轉90度。從很多東西,我已經在計算器上和其他網站發現,這應該工作(請注意,我的形象是一個正方形的圖像,其寬度和高度爲464):旋轉UIImage:無法使其工作

- (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

我能解決我的問題。這裏是我的解決方案,使用CGImageRef和[UIImage的imageWithCGImage:規模:方向:]

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];` 
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 
+0

我曾嘗試使用的UIImageView,但改造後,訪問myImageView.image只會給你的原始圖像,而不是旋轉的圖像。有沒有辦法從UIImageView獲取轉換後的圖像? –

+0

你需要在這裏玩:(3.14159265/2);嘗試任何其他值而不是2.並注意圖像變換中的變化。 – iscavengers

+0

我注意到在ImageView中轉換的圖像。但是,我想要將轉換後的圖像發送給服務器,myImageView.image不會給我轉換後的圖像。 –