调整图像大小时添加细白线
当我们调整图像大小时(下载之后并将其存储在文档目录之前),通过以下代码:
-(UIImage *)resizeImage:(UIImage *)image withSize:(CGSize)newSize
{
float actualHeight = image.size.height;
float actualWidth = image.size.width;
float imgRatio = actualWidth/actualHeight;
float maxRatio = newSize.width/newSize.height;
if(imgRatio!=maxRatio){
if(imgRatio < maxRatio){
imgRatio = newSize.width / actualHeight;
actualWidth = imgRatio * actualWidth;
actualHeight = newSize.width;
}
else{
imgRatio = newSize.height / actualWidth;
actualHeight = imgRatio * actualHeight;
actualWidth = newSize.height;
}
}
CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);
UIGraphicsBeginImageContext(rect.size);
[image drawInRect:rect];
UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//[resizedImage release];
return [resizedImage autorelease];
}
这会生成一个调整大小的图像,并在其方向上添加细白线(就像图像是横向的一样,白线添加到其底部)如果图像是纵向,则在其右手添加白线)。
请教一下,如何去掉那条白线?
谢谢。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尽管大小以浮点单位指定,但实际图像始终是整数个像素。
当您计算新尺寸以保留纵横比时,通常只有一侧为整数像素,而另一侧则缩放为具有一些小数部分。然后,当您将旧图像绘制到该矩形中时,它并不能完全填充新图像。因此,您看到的白线是图形系统渲染部分图像、部分背景的像素的方式。
从本质上讲,你想做的事情不太可能,所以你需要以某种方式捏造它。有几种可能性:
缩放图像,使得纵横比不被完美保留,但您有整数值,例如通过舍入:
保持纵横比但剪裁分数边缘。最简单的方法可能是使图像上下文变小一点:
首先用一些比白色不那么明显的颜色填充背景。显然,这是一个可怕的拼凑,但在适当的情况下可能会有效,例如,如果您总是在黑色背景下绘制图像。
另外,您不能在
return
之后调用任何内容,因此您的最终release
行不会执行任何操作。这也是因为从UIGraphicsGetImageFromCurrentImageContext
返回的图像是自动释放的——无论如何你都不应该释放它。Although the size is specified in floating point units, the actual image is always an integral number of pixels.
When you calculate the new size to preserve the aspect ratio, you will typically have only one of the sides as a whole number of pixels, while the other scales to have some fractional part. When you then draw the old image into that rect, it doesn't quite fill the new image. So what you see as a white line is the graphics system's way of rendering the pixels that are part image, part background.
In essence, what you want to do is not quite possible, so you need to fudge it somehow. There are several possibilities:
Scale the image such that the aspect ratio is not perfectly preserved but you have integral values, for example by rounding:
Maintain the aspect ratio but clip the fractional edge. The easiest way to do this is probably to make the image context a little smaller:
Just fill the background first with some colour that's less obvious than white. This is a dreadful kludge, obviously, but could be effective in the right circumstances, for example if you're always drawing the image against a black background.
On a separate note, you can't call anything after
return
, so your finalrelease
line isn't doing anything. This is just as well because the image returned fromUIGraphicsGetImageFromCurrentImageContext
is autoreleased -- you should not be releasing it anyway.这段代码将解决你的问题:
This code will fix your problem: