gpt4 book ai didi

ios - 如何在 iOS 上使用 Xamarin 旋转文件中的图像

转载 作者:行者123 更新时间:2023-11-28 18:58:46 27 4
gpt4 key购买 nike

几天来我一直在尝试旋转图像,但我得到的最好结果仍然是黑色图像。

我怀疑这可能与我旋转的点有关,但我不确定。我这么说是因为我尝试了提出的整个解决方案 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 常量的含义:

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImage_Class/index.html#//apple_ref/c/tdef/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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com