作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
几天来我一直在尝试旋转图像,但我得到的最好结果仍然是黑色图像。
我怀疑这可能与我旋转的点有关,但我不确定。我这么说是因为我尝试了提出的整个解决方案 here并用 Xamarin 术语翻译,但这没有用。
这是我的代码:
public void Rotate (string sourceFile, bool isCCW){
using (UIImage sourceImage = UIImage.FromFile(sourceFile))
{
var sourceSize = sourceImage.Size;
UIGraphics.BeginImageContextWithOptions(new CGSize(sourceSize.Height, sourceSize.Width), true, 1.0f);
CGContext bitmap = UIGraphics.GetCurrentContext();
// rotating before DrawImage didn't work, just got the image cropped inside a rotated frame
// bitmap.RotateCTM((float)(isCCW ? Math.PI / 2 : -Math.PI / 2));
// swapped Width and Height because the image is rotated
bitmap.DrawImage(new CGRect(0, 0, sourceSize.Height, sourceSize.Width), sourceImage.CGImage);
// rotating after causes the resulting image to be just black
bitmap.RotateCTM((float)(isCCW ? Math.PI / 2 : -Math.PI / 2));
var resultImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
if (targetFile.ToLower().EndsWith("png"))
resultImage.AsPNG().Save(sourceFile, true);
else
resultImage.AsJPEG().Save(sourceFile, true);
}
}
最佳答案
您似乎想要获取一个 UIImage
,然后将其顺时针旋转 90 度或逆时针旋转 90 度。实际上,您只需几行代码即可完成此操作:
public void RotateImage(ref UIImage imageToRotate, bool isCCW)
{
var imageRotation = isCCW ? UIImageOrientation.Right : UIImageOrientation.Left;
imageToRotate = UIImage.FromImage(imageToRotate.CGImage, imageToRotate.CurrentScale, imageRotation);
}
我们使用接受 3 个参数的 UIImage.FromImage()
。第一个是 CGImage
,我们可以从中获取您尝试旋转的 UIImage
。第二个参数是图像的比例。第三个参数很重要。我们可以使用 UIImageOrientation.Right
(逆时针 90 度)或 UIImageOrientation.Left
(顺时针 90 度)旋转它。您可以查看 Apple 文档以了解其他 UIImageOrientation 常量的含义:
更新:请注意,上面的代码仅更改 EXIF 标志,并且调用它两次不会将图像旋转 180 度。
添加此代码使结果累积:
UIGraphics.BeginImageContextWithOptions(new CGSize((float)h, (float)w), true, 1.0f);
imageToRotate.Draw(new CGRect(0, 0, (float)h, (float)w));
var resultImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
imageToRotate = resultImage;
关于ios - 如何在 iOS 上使用 Xamarin 旋转文件中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28635939/
我是一名优秀的程序员,十分优秀!