Objective c 在将NSImage绘制到不同大小的矩形中时,如何避免插值瑕疵?
我的最终目标是用NSImage填充任意大小的矩形。我想:Objective c 在将NSImage绘制到不同大小的矩形中时,如何避免插值瑕疵?,objective-c,cocoa,image-processing,nsimage,Objective C,Cocoa,Image Processing,Nsimage,我的最终目标是用NSImage填充任意大小的矩形。我想: 填充整个矩形 保留图像的纵横比 尽可能多地显示图像,同时保持1)和2) 当并非所有图像都能显示时,向中心裁剪 这证明了我在努力做什么。顶部的船的原始图像被绘制成各种大小的矩形 好的,到目前为止还不错。为此,我在NSImage中添加了一个类别 @implementation NSImage (Fill) /** * Crops source to best fit the destination * * destRect is t
@implementation NSImage (Fill)
/**
* Crops source to best fit the destination
*
* destRect is the rect in which we want to draw the image
* sourceRect is the rect of the image
*/
-(NSRect)scaleAspectFillRect:(NSRect)destRect fromRect:(NSRect)sourceRect
{
NSSize sourceSize = sourceRect.size;
NSSize destSize = destRect.size;
CGFloat sourceAspect = sourceSize.width / sourceSize.height;
CGFloat destAspect = destSize.width / destSize.height;
NSRect cropRect = NSZeroRect;
if (sourceAspect > destAspect) { // source is proportionally wider than dest
cropRect.size.height = sourceSize.height;
cropRect.size.width = cropRect.size.height * destAspect;
cropRect.origin.x = (sourceSize.width - cropRect.size.width) / 2;
} else { // dest is proportionally wider than source (or they are equal)
cropRect.size.width = sourceSize.width;
cropRect.size.height = cropRect.size.width / destAspect;
cropRect.origin.y = (sourceSize.height - cropRect.size.height) / 2;
}
return cropRect;
}
- (void)drawScaledAspectFilledInRect:(NSRect)rect
{
NSRect imageRect = NSMakeRect(0, 0, [self size].width, [self size].height);
NSRect sourceRect = [self scaleAspectFillRect:rect fromRect:imageRect];
[[NSGraphicsContext currentContext]
setImageInterpolation:NSImageInterpolationHigh];
[self drawInRect:rect
fromRect:sourceRect
operation:NSCompositeSourceOver
fraction:1.0 respectFlipped:YES hints:nil];
}
@end
当我想将图像绘制到某个矩形中时,我调用:
[myImage drawScaledAspectFilledInRect:onScreenRect];
除了一个问题外,它工作得非常好。在某些尺寸下,图像看起来相当模糊:
我的第一个想法是需要绘制整数像素,所以在绘制之前我使用了NSIntegralRect()。不走运
当我想到它时,我想这可能是插值的结果。要从较大的图像绘制到较小的图像,绘制矩形图像必须进行插值。模糊的图像很可能只是一种情况,其中的值映射得不太好,我们最终会出现一些无法避免的不良瑕疵
所以,问题是:如何选择一个避免这些工件的最佳矩形?我可以在绘图之前调整draw rect或crop rect来避免这种情况,但我不知道如何或何时调整它们