我正在尝试制作一个可以使用 CGContextDrawImage(…) 绘制大型(比如 2048 x 1537)图像的一部分的对象。它工作得很好,除了它非常模糊。我正在使用覆盖 drawLayer:inContext: 的“drawingController”
-(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);
}
这就是我设置自定义图像托管 View 的方式:
- (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;
}
这是在预览中打开的类似缩放比例下与源图像一起生成的图像的一部分,因此您可以看到图像与源图像相比有多么模糊。
如您所见,我的代码生成的图像看起来很糟糕。这是怎么回事?
此外,为了完整起见,我尝试为我的 imageLayer 使用 CATiledLayer。生成的图像看起来同样糟糕。
最后一点:代码需要与 iOS 和 OSX 兼容,但我在 OSX 上进行所有测试。
编辑:感谢@Andrea,我在 CGContextDrawImage(…) 上面添加了以下内容
CGFloat scale = MAX(1,MAX(CGImageGetWidth(drawImage)/drawRect.size.width,CGImageGetHeight(drawImage)/drawRect.size.height));
layer.contentsScale = scale;
最佳答案
我不太了解 osx,但我可以给你一些建议。
- 检查注释中所述的
contentScale
属性,我还写了一个 question关于它,但我从来没有得到真正的答案 - 大部分时间模糊是由于像素不匹配,这要求系统在图像上应用抗锯齿,我看到你设置了一个
contentsRect
这个,带有contentsGravity
,可能会改变图像的比例和缩放比例,将其变成模糊图像。这里好answer关于它。 - 你的 contentGravity 是什么?
- 在第一次尝试时保持简单,你真的需要异步绘制吗?
希望这对您有所帮助。
关于ios - CGContextDrawImage 绘制大图像非常模糊,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20509203/