我想制作一个对象,可以使用CGContextDrawImage(...)绘制大图像的一部分(例如2048 x 1537)。它可以正常工作,但是非常模糊。我使用一个“drawingController”,覆盖drawLayer:inContext:如下:
-(void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx{
CGImageRef drawImage = CGImageRetain(imageToDraw);
if(drawImage) {
CGRect drawRect = CGRectMake(0, 0, 1024, 748);//Just hard coded to my window size for now.
CGContextSetInterpolationQuality(ctx, kCGInterpolationHigh);
CGContextDrawImage(ctx, drawRect, drawImage);
}
CGImageRelease(drawImage);
}
这是我设置自定义图像托管视图的方法:
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code here.
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"large" ofType:@"jpg"];
CGImageRef imageRef = [self createCGImageFromFilePath:filePath];
drawingController = [[DrawingLayerController alloc] init];
drawingController.imageToDraw = imageRef;
[self setWantsLayer:YES];
imageLayer = [[CALayer alloc] init];
imageLayer.frame = self.bounds;
imageLayer.drawsAsynchronously = YES;
imageLayer.delegate = drawingController;
[self.layer addSublayer:imageLayer];
imageLayer.contentsRect = CGRectMake(0.5, 0.265452179, 0.5, 0.486662329); //Just an example contents rect.
imageLayer.drawsAsynchronously = YES;
[imageLayer setNeedsDisplay];
[imageLayer displayIfNeeded];
}
return self;
}
这是一张与源图像在相似缩放比例下在预览中打开的图像部分,以便您可以看到与源图像相比图像有多模糊。
请看下面的图片,我的代码生成的图像看起来非常糟糕。这是怎么回事?
另外,为了完整起见,我尝试使用CATiledLayer来制作我的图像层,但生成的图像看起来同样糟糕。
最后一点说明:该代码需要与iOS和OSX兼容,但我正在OSX上进行所有测试。
编辑:感谢@Andrea,我已经在CGContextDrawImage(…)上方添加了以下内容。
CGFloat scale = MAX(1,MAX(CGImageGetWidth(drawImage)/drawRect.size.width,CGImageGetHeight(drawImage)/drawRect.size.height));
layer.contentsScale = scale;