Ios 在自定义图形中对齐文本

Ios 在自定义图形中对齐文本,ios,swift,text,alignment,drawing,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.w

我正在视图中进行自定义绘图。它基本上只是画了一个圆。我需要文本出现在圆圈的中间。我尝试使用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) 






    }

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

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)



    }
看看这个答案: