在自定义绘图中对齐文本

时间:2017-06-25 09:29:54

标签: ios swift text alignment drawing

我在视图中进行自定义绘图。它基本上只画一个圆圈。我需要文字出现在那个圆圈的中间。我尝试使用stringToDraw方法,但它将我的文本与帧起始点对齐。有没有办法对齐?

override func draw(_ rect: CGRect) {
        let arcCenter = CGPoint(x:bounds.size.width/2,y:bounds.size.height/2)

        let halfSize:CGFloat = min( bounds.size.width/2, bounds.size.height/2)
        let desiredLineWidth:CGFloat = 1    // your desired value
        let circlePath = UIBezierPath(

            arcCenter: arcCenter,
            radius: CGFloat( halfSize - (1/2) ),
            startAngle: CGFloat(0),
            endAngle:CGFloat(CGFloat.pi * 2),
            clockwise: true)




        circlePath.lineWidth = desiredLineWidth
        circlePath.stroke()


        let stringToDraw = "Text" as NSString 
        let rectToDraw = bounds 
        stringToDraw.draw(in: rectToDraw) 






    }

1 个答案:

答案 0 :(得分:1)

使用标签解决了我的问题:

override func draw(_ rect: CGRect) {
        let arcCenter = CGPoint(x:bounds.size.width/2,y:bounds.size.height/2)
        // drawRingFittingInsideView(arccenter: arcCenter)
        let halfSize:CGFloat = min( bounds.size.width/2, bounds.size.height/2)
        let desiredLineWidth:CGFloat = 1    // your desired value
        let circlePath = UIBezierPath(

            arcCenter: arcCenter,
            radius: CGFloat( halfSize - (1/2) ),
            startAngle: CGFloat(0),
            endAngle:CGFloat(CGFloat.pi * 2),
            clockwise: true)
        collisionPath = circlePath



        circlePath.lineWidth = desiredLineWidth
        circlePath.stroke()


        label.frame = bounds
        label.text = "AA"
        label.textAlignment = .center
        label.drawText(in: bounds)



    }