首页 > swift在CGLayer的上下文中画图为什么很模糊?

swift在CGLayer的上下文中画图为什么很模糊?

我在drawRect方法内进行画了一个圆,但是在创建的CGlayerContext中画图时比较模糊,而在通过UIGraphicsGetCurrentContext获取的上下文中画图却比较清晰,两种在代码上的差异只是上下文不同。

为什么会有这种问题?如何使在CGlayer中画图的也变清晰?

两种模糊程度差异,可以看出第一个是比第二个模糊的,如果网页上看不出来,代码运行一下立马可以看见。


下面是我绘图的代码。

class canvas: UIView {

    override func drawRect(rect: CGRect) {
        
        // 第一个上下文,在这个上下文中绘图清晰
        let context = UIGraphicsGetCurrentContext()
        
        let layer = CGLayerCreateWithContext(context, rect.size, nil)
        
        // 第二个上下文,在这个上下文中绘图比在第一个上下文中绘图模糊
        let layerctx = CGLayerGetContext(layer)
        
        // 具体画圆的部分,两种的区别只是第一个参数的context不同
        CGContextSetFillColorWithColor(context, UIColor.clearColor().CGColor)
        CGContextSetStrokeColorWithColor(context, UIColor.redColor().CGColor)
        CGContextSetLineWidth(context, 6)
        CGContextAddArc(context, CGRectGetMidX(rect), CGRectGetMidY(rect), 150, 0, CGFloat(2 * M_PI), 1)
        
        // 在第二个上下文中划出路径,如果画圆是在第一个上下文中,这行可以忽略
        CGContextDrawPath(layerctx, CGPathDrawingMode.FillStroke)
        
        // 把创建的层绘制到第一个上下文中
        CGContextDrawLayerAtPoint(context, CGPointZero, layer)
        
        // 在第一个上下文中划出路径
        CGContextDrawPath(context, CGPathDrawingMode.FillStroke)
    }

}

因为现在的都是retina的屏幕,像素密度不同。
所以你在新建或者获取UIGraphicsContext的时候,他默认的scale是和屏幕匹配的。
也就是

CGFloat scale = [[UIScreen mainScreen] scale];

GLayer 天生是没有支持这个缩放的。所以你想要用CGLayerRef来画图,那么必须要做相关的scale操作。

CGRect bounds = CGRectMake(0, 0, width * scale, height * scale);
CGLayerRef layer = CGLayerCreateWithContext(context, bounds.size, NULL);
CGContextRef layerContext = CGLayerGetContext(layer);

CGContextScaleCTM(layerContext, scale, scale);
bounds = CGRectMake(0, 0, width, height);
CGContextDrawLayerInRect(context, bounds, layerContext);

所以其实并不是很建议用CGLayer来画图。

【热门文章】
【热门文章】