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

发布于 2022-09-02 15:24:37 字数 1575 浏览 16 评论 0

我在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)
    }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

若相惜即相离 2022-09-09 15:24:37

因为现在的都是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来画图。

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文