UIGraphicsBeginImageContext drawInRect不准确

时间:2016-04-30 10:39:54

标签: ios objective-c uiimage drawing uigraphicscontext

我正在使用此方法来压缩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像素的白线。 有关可能原因的任何建议吗? 非常感谢你!

1 个答案:

答案 0 :(得分:2)

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

actualWidth = imgRatio * actualWidth;

actualHeight = imgRatio * actualHeight;

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

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

没有它会发生什么

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

实际上可能是(0,0,24.33, 24.33) 你可能实际上正在绘制这个尺寸的矩形,但图像必须有一个 高度和宽度的圆形像素数,因此Apple可能会将矩形向上舍入以创建图像上下文。

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

相关问题