【问题标题】:Drawing dots and lines on to a UIView在 UIView 上绘制点和线
【发布时间】:2015-12-10 15:43:43
【问题描述】:

根据我在 Apple Swift website 上找到的一个示例,我给自己做了一个学习 Swift 的练习:

如您所见,有一条河流,中间有几个点,形成一条小路。所以我开始在互联网上寻找类似的河流图像,并创建了一个 Xcode 游乐场。这就是我现在拥有的:

所以基本上我有一个UIView,其子视图包含我找到的河流图像和一个用UIBezierPath 组成的点。

我的第一个问题是:这是绘制到 UIView 的正确方法吗?我的意思是使用UIBezierPath。我的第二个问题是:如何在UIView 内的精确坐标处绘制点? (UIBezierPath 还是其他?)

更准确地说,我的意图是创建一个算法,让程序识别图像,并根据像素颜色绘制一条从河流的起点到终点的带点的线,在它之间传递中间。

【问题讨论】:

  • 这里完全可以使用 UIBezierPaths 和 CAShapeLayers 来绘制圆圈并“连接点”。 UIBezierPath 有很多方法如moveToPoint: 让你画线。然后 CAShapeLayer 可以表示该线,以便您可以添加笔触宽度、颜色等属性。

标签: ios swift drawing core-graphics


【解决方案1】:

要在UIView 上绘制UIBezierPath,请执行以下操作:

let xCoord = 10
let yCoord = 20
let radius = 8

let dotPath = UIBezierPath(ovalInRect: CGRectMake(xCoord, yCoord, radius, radius))

let layer = CAShapeLayer()
layer.path = dotPath.CGPath
layer.strokeColor = UIColor.blueColor().CGColor

drawingView.layer.addSublayer(layer)

此代码将在您的视图上绘制一个半径为 8 且坐标为 10,20 的点。

更新:Swift 4+

let xCoord = 10
let yCoord = 20
let radius = 8

let dotPath = UIBezierPath(ovalIn: CGRect(x: xCoord, y: yCoord, width: radius, height: radius))

let layer = CAShapeLayer()
layer.path = dotPath.cgPath
layer.strokeColor = UIColor.blue.cgColor

drawingView.layer.addSublayer(layer)

【讨论】:

    【解决方案2】:

    这是对等式的线条部分的尝试:

        var offset:CGFloat    = 0;    var squareWidth:Int = 20
        var squareRows:Int    = Int(view.frame.size.width/CGFloat(squareWidth))
        var squareColumns:Int = Int(view.frame.size.height/CGFloat(squareWidth))
    
        for (index,element) in (0...squareRows).enumerate(){
            for (column,element) in (0...squareColumns).enumerate(){
                // Build The Square
                let rectanglePath = UIBezierPath(roundedRect: CGRectMake(
                    view.frame.minX + CGFloat(squareWidth * index) - offset,
                    view.frame.minY + CGFloat(column * squareWidth), 20, 20
                    ),
                    cornerRadius: 0.00)
    
                // Style Square
                let a = CAShapeLayer()
                    a.path = rectanglePath.CGPath
                    a.strokeColor = UIColor.whiteColor().CGColor
                    a.fillColor = nil
                    a.opacity = 0.3
                    a.lineWidth = 1.5
                view.layer.insertSublayer(a, atIndex: 1)
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-16
      • 1970-01-01
      • 1970-01-01
      • 2014-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多