在xamarin iOS中旋转UIImage

时间:2018-04-04 13:42:08

标签: ios xamarin xamarin.forms xamarin.ios

我想在xamarin中旋转UIImage。我使用此代码但未成功获取旋转图像。

public UIImage RotateImage(UIImage image)
{
    CGImage imgRef = image.CGImage;
    float width = imgRef.Width;
    float height = imgRef.Height;
    CGAffineTransform transform = CGAffineTransform.MakeIdentity();
    RectangleF bounds = new RectangleF(0, 0, width, height);
    transform = CGAffineTransform.MakeRotation((float)Math.PI / 4);
    UIGraphics.BeginImageContext(bounds.Size);
    CGContext context = UIGraphics.GetCurrentContext();

    context.ConcatCTM(transform);
    context.DrawImage(new RectangleF(0, 0, width, height), imgRef);

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

    return imageCopy;
}

4 个答案:

答案 0 :(得分:1)

也许这可能有用:

myImage.Transform = CGAffineTransform.MakeRotation(3.14159f * Degrees / 180f);

答案 1 :(得分:0)

试试这个,只需将Objective-C转换为C#,参考here

public UIImage RotateImage(UIImage image, float degree)
{
    float Radians = degree * (float)Math.PI / 180;

    UIView view = new UIView(frame: new CGRect(0, 0, image.Size.Width, image.Size.Height));
    CGAffineTransform t = CGAffineTransform.MakeRotation(Radians);
    view.Transform = t;
    CGSize size = view.Frame.Size;

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

    context.TranslateCTM(size.Width/2, size.Height/2);
    context.RotateCTM(Radians);
    context.ScaleCTM(1, -1);

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

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

    return imageCopy;
}

答案 2 :(得分:-1)

在带有视图的Xamarin.Forms中,您拥有Rotation属性,不需要平台代码:

Image test = new Image { Rotation = 45};

答案 3 :(得分:-1)

这里提供了一种效果很好的方法:

Impl2