iOS-如何在使用自定义UIBezierPath绘制的CAShapeLayer中设置CATextLayer?

如何解决iOS-如何在使用自定义UIBezierPath绘制的CAShapeLayer中设置CATextLayer?

我要编写一个自定义饼图菜单。在下面的代码中,您将看到如何创建包含两个项目的饼图菜单。我的结构如下:我使用带有CAShapeLayer作为上下文的矩形UIBezierPath作为圆形背景。在我的圆形背景内,我有一个孩子,一个小内圈(还有带有CAShapeLayer的UIBezierPath)。我的圆形背景图层的其他子元素是项目,它们也是CAShapeLayer,使用自定义UIBezierPath(我绘制项目取决于项目的数量(不同程度,依此类推))。现在,我想在每个项目层中添加一个CATextLayer(“项目1”,“项目2”,依此类推)。我的问题是,我不知道如何设置特定项目图层的框架,以及如何以文本动态位于父项目图层内部的方式添加特定的CATextLayer。就我而言,CATextLayer取决于菜单背景层的框架。

Current Output

func setMenuBackgroundLayer() {
        //Draw a circle background with UIBezierPath for the static pie menu
        let path = UIBezierPath(arcCenter: CGPoint(x: self.frame.size.width / 2,y: self.frame.size.height / 2),radius: menuRadius,startAngle: CGFloat(0),endAngle: CGFloat(Double.pi * 2),clockwise: true)
    
        menuBackgroundLayer = CAShapeLayer()
        menuBackgroundLayer.path = path.cgPath
        menuBackgroundLayer.fillColor = menuBackgroundLayerColor.cgColor
        menuBackgroundLayer.frame = self.bounds
        menuBackgroundLayer.zPosition = 1
        
        self.layer.addSublayer(menuBackgroundLayer)
        
        //Draw the inner circle (back button)
        let pathInner = UIBezierPath(arcCenter: CGPoint(x: menuBackgroundLayer.frame.size.width / 2,y: menuBackgroundLayer.frame.size.height / 2),radius: innerCircleRadius,clockwise: true)
        
        innerCircleLayer = CAShapeLayer()
        innerCircleLayer.path = pathInner.cgPath
        innerCircleLayer.fillColor = menuBackgroundLayerColor.cgColor
        innerCircleLayer.strokeColor = UIColor.black.cgColor
        innerCircleLayer.lineWidth = 1
        innerCircleLayer.frame = menuBackgroundLayer.frame
        menuBackgroundLayer.addSublayer(innerCircleLayer)
        //Set the inner circle above all other menu items
        innerCircleLayer.zPosition = 100
        
        //Add the arrow image inside the inner circle
        //addBackImage()
    }
func insertMenuItems() {
        //Compare which item has to get inserted and insert it
        if numberOfItems == 1 {
            let path = UIBezierPath(arcCenter: CGPoint(x: menuBackgroundLayer.frame.size.width / 2,clockwise: true)
            
            item1Layer = CAShapeLayer()
            item1Layer.path = path.cgPath
            item1Layer.fillColor = menuBackgroundLayerColor.cgColor
            item1Layer.strokeColor = UIColor.black.cgColor
            item1Layer.lineWidth = 1
            item1Layer.frame = menuBackgroundLayer.bounds
            menuBackgroundLayer.addSublayer(item1Layer)
            item1Layer.zPosition = 2
            
            let textLayer = CATextLayer()
            textLayer.string = "ITEM 1"
            textLayer.foregroundColor = UIColor.white.cgColor
            textLayer.font = UIFont(name: "Avenir",size: 15.0)
            textLayer.fontSize = 15.0
            textLayer.alignmentMode = CATextLayerAlignmentMode.center
            textLayer.zPosition = 3
            textLayer.frame = item1Layer.bounds
            textLayer.position = CGPoint(x: item1Layer.position.x,y: item1Layer.position.y + 20.0)
            textLayer.contentsScale = UIScreen.main.scale
            item1Layer.addSublayer(textLayer)
        }
        else if numberOfItems == 2 {
            //Item 1
            let path1 = UIBezierPath()
            path1.move(to: CGPoint(x: menuBackgroundLayer.frame.size.width / 2,y: menuBackgroundLayer.frame.size.height / 2))
            path1.addArc(withCenter: CGPoint(x: menuBackgroundLayer.frame.size.width / 2,startAngle: rad2deg(180.0),endAngle: rad2deg(0.0),clockwise: true)
            path1.close()
            item1Layer = CAShapeLayer()
            item1Layer.path = path1.cgPath
            item1Layer.fillColor = menuBackgroundLayerColor.cgColor
            item1Layer.strokeColor = UIColor.black.cgColor
            item1Layer.lineWidth = 1
            item1Layer.frame = menuBackgroundLayer.bounds
            menuBackgroundLayer.addSublayer(item1Layer)
            item1Layer.zPosition = 2
            
            let textLayer1 = CATextLayer()
            textLayer1.string = "ITEM 1"
            textLayer1.foregroundColor = UIColor.white.cgColor
            textLayer1.font = UIFont(name: "Avenir",size: 15.0)
            textLayer1.fontSize = 15.0
            textLayer1.alignmentMode = CATextLayerAlignmentMode.center
            textLayer1.zPosition = 3
            textLayer1.frame = item1Layer.bounds
            textLayer1.position = CGPoint(x: item1Layer.position.x,y: item1Layer.position.y + 20.0)
            textLayer1.contentsScale = UIScreen.main.scale
            item1Layer.addSublayer(textLayer1)
            
            //Item 2
            let path2 = UIBezierPath()
            path2.move(to: CGPoint(x: menuBackgroundLayer.frame.size.width / 2,y: menuBackgroundLayer.frame.size.height / 2))
            path2.addArc(withCenter: CGPoint(x: menuBackgroundLayer.frame.size.width / 2,startAngle: rad2deg(0.0),endAngle: rad2deg(180.0),clockwise: true)
            path2.close()
            item2Layer = CAShapeLayer()
            item2Layer.path = path2.cgPath
            item2Layer.fillColor = menuBackgroundLayerColor.cgColor
            item2Layer.strokeColor = UIColor.black.cgColor
            item2Layer.lineWidth = 1
            item2Layer.frame = menuBackgroundLayer.bounds
            menuBackgroundLayer.addSublayer(item2Layer)
            item2Layer.zPosition = 2
            
            let textLayer2 = CATextLayer()
            textLayer2.string = "ITEM 2"
            textLayer2.foregroundColor = UIColor.white.cgColor
            textLayer2.font = UIFont(name: "Avenir",size: 15.0)
            textLayer2.fontSize = 15.0
            textLayer2.alignmentMode = CATextLayerAlignmentMode.center
            textLayer2.zPosition = 3
            textLayer2.frame = item2Layer.bounds
            textLayer2.position = CGPoint(x: item2Layer.position.x,y: item2Layer.position.y + 20.0)
            textLayer2.contentsScale = UIScreen.main.scale
            item2Layer.addSublayer(textLayer2)
        }
and so on...
}

解决方法

因此,这是一个粗糙的原型,可以满足您的需要,但不够精确。 enter image description here

如果要旋转文本,可以使用CATransform来实现。 您可以在此处使用以下代码:https://github.com/gatamar/stackoverflow_answers/tree/master/so64348954

或者,如果您几乎需要它,我可以更精确些。

“饼图菜单”的代码:

import Foundation
import UIKit

class HackLinesView: UIView {
    init(frame: CGRect,partsCount parts: Int) {
        super.init(frame: frame)
        backgroundColor = .clear
        
        let side = frame.width/2
        // add lines
        for part in 0..<parts {
            let angle = CGFloat(part)/CGFloat(parts) * 2 * .pi
            let lineLayer = CAShapeLayer()
            lineLayer.backgroundColor = UIColor.black.cgColor
            let path = UIBezierPath(rect: CGRect(x: 0,y: 0,width: 1,height: side))
            lineLayer.path = path.cgPath
            lineLayer.transform = CATransform3DMakeRotation(angle,1)
            layer.addSublayer(lineLayer)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
    
class PieMenuView: UIView {
    init(frame: CGRect,partsCount parts: Int) {
        assert( abs(frame.width-frame.height) < 0.001)
        super.init(frame: frame)
        setupLayers(parts)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupLayers(_ parts: Int) {
        let side = bounds.width
        let outerRadius = side * 0.5
        let innerRadius = side * 0.2
        
        // add outer circle
        let outerCircleLayer = CAShapeLayer()
        outerCircleLayer.frame = bounds
        outerCircleLayer.cornerRadius = outerRadius
        outerCircleLayer.backgroundColor = UIColor.orange.cgColor
        layer.addSublayer(outerCircleLayer)
        
        // add inner circle
        let innerCircleLayer = CAShapeLayer()
        innerCircleLayer.frame = CGRect(x: side/2-innerRadius,y: side/2-innerRadius,width: innerRadius*2,height: innerRadius*2)
        innerCircleLayer.cornerRadius = innerRadius
        innerCircleLayer.backgroundColor = UIColor.yellow.cgColor
        layer.addSublayer(innerCircleLayer)
        
        let linesView = HackLinesView(frame: CGRect(x: side/2,y: side/2,width: side,height: side),partsCount: parts)
        addSubview(linesView)
        
        // add text
        for part in 0..<parts {
            let angle = CGFloat(part)/CGFloat(parts) * 2 * .pi
            
            let textLayer = CATextLayer()
            textLayer.string = String(format: "%d",part)
            textLayer.foregroundColor = UIColor.blue.cgColor
            
            // calc the center for text layer
            let x1 = side/2
            let y1 = side/2
            let x2 = x1 + cos(angle)*outerRadius
            let y2 = y1 + sin(angle)*outerRadius
            
            let textCenterX = (x1 + x2)/2,textCenterY = (y1 + y2)/2
            let textLayerSide: CGFloat = 50
            
            textLayer.frame = CGRect(x: textCenterX-textLayerSide/2,y: textCenterY-textLayerSide/2,width: textLayerSide,height: textLayerSide)
            
            layer.addSublayer(textLayer)
        }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res