美文网首页SwiftUISwiftUI
SwiftUI Shape 三句代码自绘 心形

SwiftUI Shape 三句代码自绘 心形

作者: Renew全栈工程师 | 来源:发表于2021-03-18 01:53 被阅读0次

1.因为在项目中有双击点赞特效,起先用 2 个 Circle + 1 个 Rectangle 实现心形, 但是设置父View 的 opacity 时候 颜色叠加了

     Group {
            ZStack{
               Rectangle()
                    .fill(Color.red)
                   .frame(width: 100, height: 100)
                Circle()
                    .fill(Color.red)
                   .offset(x:0,y: -50)
                   .frame(width: 100, height: 100)

               Circle()
                   .fill(Color.red)
                   .offset(x: 50,y:0)
                   .frame(width: wh, height: wh)
            }
           .rotationEffect(Angle(degrees: -45)
        }
        .opacity(0.6)
第一次实现效果

然后想着各种办法解决这个问题,发现没找到(如果有能解决的小伙伴可以帮忙解决下哦)

2.第二次改用 Shape来实现了

/// 定义一个心形类 继承 Shape 实现 path 方法
struct HeartShape : Shape {
    
    func path(in rect: CGRect) -> Path {
        /// 新建一个path路径
        var path = Path() 
        
        /// 先添加一个矩形上去 大小又 rect 参数决定
        path.addPath(Rectangle().path(in: rect)) 

        /// 在添加一个圆,添加到左边 大小还是  rect 参数决定 大,但是 y 是 也就是top 是高度的一半 的 负值,也是 top 往上移动
        let circleRectLeft = CGRect(x: 0, y: -(rect.height / 2), width: rect.width, height: rect.height)
        
        path.addPath(Circle().path(in: circleRectLeft))
        
        /// 在添加一个圆,添加到又边 大小还是  rect 参数决定 大,但是 x 是 也就是left 是宽度的一半
        let circleRectRight = CGRect(x: (rect.width / 2), y: 0, width: rect.width, height: rect.height)
        
        path.addPath(Circle().path(in: circleRectRight))
        
        return path
    }
}

/// View 调用
var body: some View{
  HeartShape()
    .fill(Color.red)
    .frame(width: 100, height: 100)
    .rotationEffect(Angle(degrees: Int.random(in: -60 ... -30)))
    .scaleEffect(2)
    .opacity(.6)
}
HeartShape 完美实现

3.下面是双击点赞视频,需要的可以私信我要源代码

SwiftUI 双击点赞动画

相关文章

网友评论

    本文标题:SwiftUI Shape 三句代码自绘 心形

    本文链接:https://www.haomeiwen.com/subject/kwnycltx.html