我通过UIBezierPath创建了一个Circle形状,然后将其设置为可以拖动的CAShapeLayer。另外,我在我的xcode项目中添加了PNG图像(30px,30px)。 我将PNG图像添加到CAShapeLayer中,但每次我移动它'切割'时都会看不到球的某些部分:
这是PNG图片:
到目前为止,这是我的代码:
class ViewController: UIViewController, UIGestureRecognizerDelegate {
var shapeLayer2 = CAShapeLayer()
var circlePath2 = UIBezierPath()
override func viewDidLoad() {
super.viewDidLoad()
let angleEarth: Double = 0
let angleEarthAfterCalculate: CGFloat = CGFloat(angleEarth*M_PI/180) - CGFloat(M_PI/2)
let earthX = midViewX + cos(angleEarthAfterCalculate)*100
let earthY = midViewY + sin(angleEarthAfterCalculate)*100
circlePath2 = UIBezierPath(arcCenter: CGPoint(x: earthX,y: earthY), radius: CGFloat(10), startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)
shapeLayer2.path = circlePath2.CGPath
shapeLayer2.fillColor = UIColor.blueColor().CGColor
shapeLayer2.strokeColor = UIColor.clearColor().CGColor
shapeLayer2.lineWidth = 7
view.layer.addSublayer(shapeLayer2)
let dragBall = UIPanGestureRecognizer(target: self, action:#selector(ViewController.dragBall(_:)))
view.addGestureRecognizer(dragBall)
let image = UIImage(named: "rrr.png")
if let realImage = image {
let color = UIColor(patternImage: image!)
shapeLayer2.fillColor = color.CGColor
shapeLayer4.fillColor = color.CGColor
}
@IBAction func dragBall(recognizer: UIPanGestureRecognizer) {
let point = recognizer.locationInView(self.view)
let earthX = Double(point.x)
let earthY = Double(point.y)
let midViewXDouble = Double(midViewX)
let midViewYDouble = Double(midViewY)
let angleX = (earthX - midViewXDouble)
let angleY = (earthY - midViewYDouble)
angle = atan2(angleY, angleX)
let earthX2 = midViewXDouble + cos(angle)*100
let earthY2 = midViewYDouble + sin(angle)*100
circlePath2 = UIBezierPath(arcCenter: CGPoint(x: earthX2,y: earthY2), radius: CGFloat(10), startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)
shapeLayer2.path = circlePath2.CGPath
}
快捷方式:如果没有在gif中获得结果,我无法将PNG图像放入CAShapeLayer。