You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:Xamarin iOS中UIImage旋转代码无法生成正确旋转图像

解决Xamarin中UIImage旋转无效的问题

我来帮你排查下这段旋转UIImage代码的问题哈~你的代码目前有几个关键环节没处理到位,导致无法生成正确的旋转后图像,下面给你梳理并修正:

原代码的核心问题

  • 旋转后图像的实际尺寸会超出原宽高范围,但你仍使用原尺寸的bounds,导致旋转后的图像被裁剪或显示不全
  • 没有将创建的旋转变换(transform)应用到绘图上下文(CGContext)中
  • 代码未完整实现图像绘制和最终获取UIImage的收尾步骤

修正后的完整代码

public UIImage RotateImage(UIImage image)
{
    if (image == null) return null;

    CGImage imgRef = image.CGImage;
    float width = imgRef.Width;
    float height = imgRef.Height;
    var rotationAngle = (float)Math.PI / 4; // 45度旋转

    // 计算旋转后的实际尺寸,避免图像被裁剪
    var rotatedSize = new SizeF(
        (float)(Math.Abs(width * Math.Cos(rotationAngle)) + Math.Abs(height * Math.Sin(rotationAngle))),
        (float)(Math.Abs(height * Math.Cos(rotationAngle)) + Math.Abs(width * Math.Sin(rotationAngle)))
    );

    // 创建支持Retina屏幕的图像上下文,保证图像清晰度
    UIGraphics.BeginImageContextWithOptions(rotatedSize, false, image.CurrentScale);
    CGContext context = UIGraphics.GetCurrentContext();

    // 平移上下文到旋转后的中心,避免图像偏移
    context.TranslateCTM(rotatedSize.Width / 2, rotatedSize.Height / 2);
    // 应用旋转变换
    context.RotateCTM(rotationAngle);
    // 再平移回原图像的中心位置,确保绘制位置正确
    context.TranslateCTM(-width / 2, -height / 2);

    // 将原图像绘制到上下文
    image.Draw(new RectangleF(0, 0, width, height));

    // 获取旋转后的UIImage并收尾上下文
    UIImage rotatedImage = UIGraphics.GetImageFromCurrentImageContext();
    UIGraphics.EndImageContext();

    return rotatedImage;
}

关键细节说明

  • 用UIGraphics.BeginImageContextWithOptions替代UIGraphics.BeginImageContext:第二个参数设为false支持透明背景,第三个参数传入原图像的CurrentScale,确保Retina屏幕下图像不模糊
  • 计算rotatedSize:通过三角函数算出旋转后图像的实际宽高,彻底解决图像被裁剪的问题
  • 上下文平移操作:先把原点移到新尺寸中心,旋转后再移回原图像中心,保证旋转后的图像居中显示,不会偏移出画布范围

内容的提问来源于stack exchange,提问作者Mannu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:43:48