【问题标题】:iOS the quality of drawing lines using CGContext is much worse than SKShapeNode in SpriteKitiOS使用CGContext画线的质量比SpriteKit中的SKShapeNode差很多
【发布时间】:2016-06-23 02:01:33
【问题描述】:

我正在制作一个用户可以用手指画线的游戏。网站上有很多方法。我尝试了两种方法,一种在 UIView (UIKit) 中使用 CGContext,另一种在 SpriteKit 中使用 CGPath 和 SKShapeNode。但后者显示出更好的质量。第一个使用 CGContext 有丑陋的粗糙边缘。

请查看以下屏幕截图。我还在此处附上了这两种方法的部分代码(在touchesMove 函数中)。

注意:var ref = CGPathCreateMutable()

UIView 中的CGContext

    CGPathAddLineToPoint(ref, nil, currentPoint.x, currentPoint.y)

    UIGraphicsBeginImageContext(self.frame.size)
    let context = UIGraphicsGetCurrentContext()
    tempImageView.image?.drawInRect(CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height))


    CGContextAddPath(context, ref)

    // 3
    CGContextSetLineCap(context, CGLineCap.Round)
    CGContextSetLineWidth(context, brushWidth)
    CGContextSetRGBStrokeColor(context, red, green, blue, 1.0)
    CGContextSetBlendMode(context, CGBlendMode.Normal)

    // 4
    CGContextStrokePath(context)

    // 5
    UIGraphicsEndImageContext()

SpriteKit 中的 SKShapeNode 注:var lineDrawing = SKShapeNode()

CGPathAddLineToPoint(ref, nil, location.x, location.y)
lineDrawing.path = ref
lineDrawing.lineWidth = 3
lineDrawing.strokeColor = UIColor.blackColor()
lineDrawing.alpha = 1.0
self.addChild(lineDrawing)

如何在 UIView 中画出与 SKShapeNode 相同质量的线条?

【问题讨论】:

  • 打印实际路径。我的猜测是每条路径都有不同数量的路径。

标签: ios swift uiview sprite-kit cgcontext


【解决方案1】:

一个明显的问题是您使用了一个不能处理 Retina 屏幕的过时函数:

UIGraphicsBeginImageContext(self.frame.size)

你应该改用这个:

UIGraphicsBeginImageContextWithOptions(self.frame.size, false, 0)

WithOptions 版本以 0 作为最后一个参数,如果设备具有 Retina 屏幕,则以 Retina 分辨率创建图像上下文。 (参数 0 表示“使用设备屏幕的比例因子”。)

可能还有其他问题,因为您没有显示为每个测试用例在路径中创建点的代码。

【讨论】:

  • 更好,但仍然不如 SKShapeNode。创建路径的代码如:(1)var ref = CGPathCreateMutable(); (2)in touchesBegan, CGPathMoveToPoint(ref, nil, location.x, location.y); (3) 在 touchesMove 中,CGPathAddLineToPoint(ref, nil, location.x, location.y)。我错过了什么吗?
  • 位置在哪里let location = touch.locationInView(self)
  • 尝试在两个测试中以相同的速度绘制相同的形状(用手指或其他任何东西)。在CGContext 实现中路径最终有多少点? SpriteKit 版本有多少个?
  • 不知道为什么我把这个设置为 1.0。刚刚改进了我自己的游戏。
  • @robmayoff 我认为你是对的。我有多个UIGraphicsBeginImageContext 行,我在其中进行屏幕截图并转换为图像并分析像素信息。只更改一行是行不通的,但是当我更改所有行时它会起作用。但是,双倍像素会耗尽我的 CPU,因为我正在进行大量像素编辑。所以我最后不得不坚持过时的功能并添加self.layer.shouldRasterize = true以使其更好,虽然不如视网膜功能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-10
  • 1970-01-01
  • 2016-05-25
相关资源
最近更新 更多