Xamarin UIImage旋转
问题描述:
我尝试旋转图像并保存,当我保存图像时,它可以正常工作,但是当我尝试旋转图像时,旋转工作但图像为空。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;
}
这里是我得到:
与原始图像:
更新:小码变化
答
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();
我认为图像是空白的,因为没有图像和创建的上下文之间的关系定义。 – NeverHopeless
正如你可以在代码中看到(注释)我试图通过context.DrawImage但没有成功链接我们。然后,我尝试originalImage.Draw,但再次空白图像。 – Leze
请你把阐明你有问题吗?你分享的代码旋转图像就好了,我用我的测试应用程序检查过它。我还建议在'using()'中使用'UIGraphics.BeginImageContext(rotatedSize)'。 –