swiftUI虚拟摇杆

代码

import SwiftUI

extension CGPoint {
    func distance(to point: CGPoint) -> CGFloat {
        return sqrt(pow((point.x - x), 2) + pow((point.y - y), 2))
    }
}

struct SwiftUIView: View {
    
    @State private var position = CGPoint(x: 100, y: 100)
    private var dragDiametr: CGFloat = 200.0
    var body: some View {
        
        VStack{
            Text("current position = (x: \(Int(position.x)), y: \(Int(position.y)))")
            Circle()
                .fill(Color.red)
                .frame(width: dragDiametr, height: dragDiametr)
                .overlay(
                    Circle()
                        .fill(Color.black)
                        .frame(width: dragDiametr / 4, height: dragDiametr / 4)
                        .position(x: position.x, y: position.y)
                        .gesture(DragGesture()
                            .onChanged(){value in
                                let currentLocation = value.location
                                let center = CGPoint(x: self.dragDiametr/2, y: self.dragDiametr/2)
                                let distance = center.distance(to:currentLocation)
                                if distance > self.dragDiametr / 2 {
                                    let k = (self.dragDiametr / 2) / distance
                                    let newLocationX = (currentLocation.x - center.x) * k+center.x
                                    let newLocationY = (currentLocation.y - center.y) * k+center.y
                                    self.position = CGPoint(x: newLocationX, y: newLocationY)
                                }else{
                                    self.position = value.location
                                }
                            }
                            .onEnded({ value in
                                position = CGPoint(x: 100, y: 100)
                            })
                        )
                )
        }
    }
}

参考文档

原文

搬运

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值