ios - 对齐自定义绘图中的文本

标签 ios swift text alignment drawing

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



    }

关于ios - 对齐自定义绘图中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44745010/

相关文章:

javascript - 将变量与测试字符串进行比较

ios - TabBarController 中的 UIImagePickerController

ios - 使用 Facebook SDK 构建项目时出现链接器错误

android - 如何在Flutter中设置TextSpan的圆角

ios - 将 gestureRecognizer 添加到 tableView 单元格

java - 使用java搜索并打印文本文件

ios - 将底线边框添加到 TextView - iOS

ios - 将值传递给与 uiview 关联的类并让 draw 识别值而不是默认类值

objective-c - NSTabViewItem 按钮标签可以调整大小吗?

javascript - 交叉文本以找到常用词