【问题标题】:Why drawing straight lines using Core Graphics I get "dashed" lines?为什么使用 Core Graphics 绘制直线我得到“虚线”?
【发布时间】:2016-01-09 11:50:21
【问题描述】:

我尝试使用以下 swift 代码绘制一个图标,但我得到了“虚线”。我刚刚使用了moveToPointaddLineToPoint 函数。正如您在下图中看到的那样,我也遇到了与其他绘图相同的图形故障。我使用 Xcode 7.2 并在 iOS 9.2.1 上运行代码。

@IBDesignable class DeleteButton: UIButton {

    override func drawRect(rect: CGRect) {

        UIColor.blackColor().setStroke()
        let lineWidth = CGFloat(1)

        // Draw empty circle
        let frame = CGRect(x: rect.origin.x + lineWidth, y: rect.origin.y + lineWidth, width: rect.width - (lineWidth * 2), height: rect.height - (lineWidth * 2))
        let path = UIBezierPath(ovalInRect: frame)
        path.lineWidth = lineWidth

        path.stroke()

        // Draw X
        let radius = (rect.width / 2) * 0.5
        let center = CGPoint(x: rect.width / 2, y: rect.height / 2)

        let π = CGFloat(M_PI)
        let centerWidth = radius * cos(π/4)
        let centerHeight = radius * sin(π/4)

        path.lineWidth = lineWidth

        path.moveToPoint(CGPoint(x: CGFloat(center.x + centerWidth), y: CGFloat(center.y + centerHeight)))
        path.addLineToPoint(CGPoint(x: CGFloat(center.x - centerWidth), y: CGFloat(center.y - centerHeight)))
        path.stroke()

        path.lineWidth = lineWidth

        path.moveToPoint(CGPoint(x: center.x - centerWidth, y: center.y + centerHeight))
        path.addLineToPoint(CGPoint(x: center.x + centerWidth, y: center.y - centerHeight))
        path.stroke()
    }
}

这是结果:

我为我糟糕的英语道歉。

【问题讨论】:

    标签: ios swift drawing core-graphics


    【解决方案1】:

    我相信您看到的是按钮标题文本在图像上绘制的结果。在 Playground 中使用您的代码查看以下演示:

    【讨论】:

      【解决方案2】:

      我们需要知道该代码运行的上下文。你不能只是开始画画。

      在视图中绘制的常用方法是重写 drawRect 方法。当您这样做时,系统会使用蒙版正确设置图形上下文,将您的绘图剪辑到视图的边界,将坐标系设置为视图的坐标等。

      如果您的绘图代码不在视图的 drawRect 方法中,那是您的问题。

      【讨论】:

      • 这很奇怪。绘图上下文可能有一个虚线集,或者可能有一个遮罩处于活动状态,它覆盖了您的绘图的一部分。尝试在绘图上下文中使用 CGContextSetLineDash 并使用 nil 数组和 0 计数。如果您只是创建一个与整个视图大小相同的矩形贝塞尔路径并用纯色填充它会发生什么?你还在上面看到白色吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-23
      • 1970-01-01
      • 2015-02-22
      相关资源
      最近更新 更多