【问题标题】:UIGraphicsBeginImageContext drawInRect inaccurateUIGraphicsBeginImageContext drawInRect 不准确
【发布时间】:2016-04-30 10:39:54
【问题描述】:

我用这个方法压缩UIImage

if (actualHeight > maxHeight || actualWidth > maxWidth)
    {
        if(imgRatio < maxRatio)
        {
            //adjust width according to maxHeight
            imgRatio = maxHeight / actualHeight;
            actualWidth = imgRatio * actualWidth;
            actualHeight = maxHeight;
        }
        else if(imgRatio > maxRatio)
        {
            //adjust height according to maxWidth
            imgRatio = maxWidth / actualWidth;
            actualHeight = imgRatio * actualHeight;
            actualWidth = maxWidth;
        }
        else
        {
            actualHeight = maxHeight;
            actualWidth = maxWidth;
        }
    }
 CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);
    UIGraphicsBeginImageContext(rect.size);
    [image drawInRect:rect];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    NSData *imageData = UIImageJPEGRepresentation(img, compressionQuality);
    UIGraphicsEndImageContext();

但是对于一些UIImage,在它们的底部,有一条1像素的白线。 对可能的原因有什么建议吗? 非常感谢!

【问题讨论】:

    标签: ios objective-c uiimage drawing uigraphicscontext


    【解决方案1】:

    问题可能是您正在使用 CGFloats 并且您正在对它们进行乘法/除法,这会导致非整数坐标。

    线

    actualWidth = imgRatio * actualWidth;
    

    actualHeight = imgRatio * actualHeight;
    

    可能会导致非整数坐标。使用ceilffloorfroundf 来解决此问题。例如

    actualWidth = ceilf(imgRatio * actualWidth);
    actualHeight = ceilf(imgRatio * actualHeight);
    

    没有它会发生什么

    CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);
    

    实际上可能是(0,0,24.33, 24.33) 您实际上可能正在绘制这种大小的矩形,但图像必须具有 高度和宽度的四舍五入像素数,因此Apple可能会将矩形四舍五入以创建图像上下文。

    但是他们可能会使用抗锯齿来绘制它,因此它在视觉上看起来确实像非整数像素。这就是为什么你会得到白线,也可能会损失质量。

    【讨论】:

    • 感谢您的详细回复!我怀疑这种行为,但我没有靠近我的电脑来检查它!如果我可以的话,只是一个小问题:一般来说,有可能画出反圆/不是主要数字,至于(100.56,34.6)?还是苹果 API 会自动舍入它(在这种情况下,我看不到可能的解决方案)?非常感谢!
    • 添加 ceil 解决了问题,太棒了!非常感谢!
    • 即使你可以这样画,也无法在设备上显示。设备能做的最好的事情就是对整个图片进行抗锯齿处理——这使得它超级模糊——你不希望这样。
    • 没错。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2015-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    相关资源
    最近更新 更多