2016-10-04 118 views
0

我嘗試旋轉圖像並保存,當我保存圖像時,它可以正常工作,但是當我嘗試旋轉圖像時,旋轉工作但圖像爲空。Xamarin UIImage旋轉

public UIImage RotateImage (UIImage originalImage, int rotationAngle) 
     { 
      UIImage rotatedImage = originalImage; 

      if (rotationAngle > 0) { 
       CGSize rotatedSize; 
       float angle = Convert.ToSingle ((Math.PI/180) * rotationAngle); 

       using (UIView rotatedViewBox = new UIView (new CGRect (0, 0, originalImage.Size.Width, originalImage.Size.Height))) { 
        CGAffineTransform t = CGAffineTransform.MakeRotation (angle); 
        rotatedViewBox.Transform = t; 
        rotatedSize = rotatedViewBox.Frame.Size; 

        UIGraphics.BeginImageContext (rotatedSize); 
        CGContext context = UIGraphics.GetCurrentContext(); 

        context.TranslateCTM (rotatedSize.Width/2, rotatedSize.Height/2); 
        context.RotateCTM (angle); 
        context.ScaleCTM ((nfloat)1.0, -(nfloat)1.0); 

        context.DrawImage (new CGRect (-originalImage.Size.Width/2, -originalImage.Size.Height/2, originalImage.Size.Width, originalImage.Size.Height), originalImage.CGImage); 

        rotatedImage = UIGraphics.GetImageFromCurrentImageContext(); 

        UIGraphics.EndImageContext(); 
       } 

      } 

      return rotatedImage; 
     } 

這裏是我得到:

Rotated image

與原始圖像:

original image

更新:小碼變化

+0

我認爲圖像是空白的,因爲沒有圖像和創建的上下文之間的關係定義。 – NeverHopeless

+0

正如你可以在代碼中看到(註釋)我試圖通過context.DrawImage但沒有成功鏈接我們。然後,我嘗試originalImage.Draw,但再次空白圖像。 – Leze

+0

請你把闡明你有問題嗎?你分享的代碼旋轉圖像就好了,我用我的測試應用程序檢查過它。我還建議在'using()'中使用'UIGraphics.BeginImageContext(rotatedSize)'。 –

回答

0

rotate image using CGContextDrawImage

 CGImage imgRef = originalImage.CGImage; 
     float width = imgRef.Width; 
     float height = imgRef.Height; 
     CGAffineTransform transform = CGAffineTransform.MakeIdentity(); 
     RectangleF bounds = new RectangleF(0, 0, width, height); 

     float angle = Convert.ToSingle((rotationAngle/180f) * Math.PI); 
     transform = CGAffineTransform.MakeRotation(angle); 

     UIGraphics.BeginImageContext(bounds.Size); 

     CGContext context = UIGraphics.GetCurrentContext(); 

     context.TranslateCTM(width/2, height/2); 
     context.SaveState(); 
     context.ConcatCTM(transform); 
     context.SaveState(); 
     context.ConcatCTM(CGAffineTransform.MakeScale(1.0f, -1.0f)); 

     context.DrawImage(new RectangleF(-width/2, -height/2, width, height), imgRef); 
     context.RestoreState(); 

     UIImage imageCopy = UIGraphics.GetImageFromCurrentImageContext(); 
     UIGraphics.EndImageContext();