2014-11-10 11 views
6

mam ten kształt, który rysuję w drawRect()Animacja ścieżkę bezier sporządzony w drawRect() Swift

var rectanglePath = UIBezierPath() 

override func drawRect(rect: CGRect) { 
    rectanglePath = UIBezierPath(rect: self.bounds) 
    rectanglePath.fillWithBlendMode(kCGBlendModeMultiply, alpha: 0.7) 
    layer.shouldRasterize = true 
} 

Kiedy prepareForEditing funkcja jest wywoływana, chcę animowanie rectanglePath. Próbowałem:

func prepareForEditing(editing:Bool){ 
     UIView.animateWithDuration(0.5, 
      animations: { 
       self.rectanglePath = makeNewShape() 
      } 
     ) 
    } 

Nic się nie dzieje. Czy możesz mi powiedzieć, co jest nie tak z moim kodem?

Odpowiedz

8

Aby animować CGPath, nie można używać metod UIView.animation. Stworzyłem niestandardowe UIView podklasy, aby pokazać, w jaki sposób można animować CGPaths kształt, należy zapoznać się z uwagami i zmieniają je dla własnych potrzeb:

class MyView: UIView { 

let shapeLayer = CAShapeLayer() 
let maskLayer = CAShapeLayer() 
var rectanglePath = UIBezierPath() 

override func didMoveToSuperview() { 
    super.didMoveToSuperview() 

    backgroundColor = UIColor.clear 

    // initial shape of the view 
    rectanglePath = UIBezierPath(rect: bounds) 

    // Create initial shape of the view 
    shapeLayer.path = rectanglePath.cgPath 
    shapeLayer.strokeColor = UIColor.black.cgColor 
    shapeLayer.fillColor = UIColor.clear.cgColor 
    layer.addSublayer(shapeLayer) 

    //mask layer 
    maskLayer.path = shapeLayer.path 
    maskLayer.position = shapeLayer.position 
    layer.mask = maskLayer 
} 

func prepareForEditing(editing:Bool){ 

    let animation = CABasicAnimation(keyPath: "path") 
    animation.duration = 2 

    // Your new shape here 
    animation.toValue = UIBezierPath(ovalIn: bounds).cgPath 
    animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) 

    // The next two line preserves the final shape of animation, 
    // if you remove it the shape will return to the original shape after the animation finished 
    animation.fillMode = kCAFillModeForwards 
    animation.isRemovedOnCompletion = false 

    shapeLayer.add(animation, forKey: nil) 
    maskLayer.add(animation, forKey: nil) 
    } 
} 
+0

Dzięki przy okazji! Czy tryb 'fillWithBlend' działa z ShapeLayers? Próbowałem tego w ten sposób i mieszanie w ogóle nie działało. –

+0

Wierzę, że jeśli dodasz funkcję drawRect do klasy MyView (dokładnie tak, jak z 3 liniami kodu), wszystko powinno być, jak chcesz. – Greg

+0

Dlaczego narysowałeś kształt w 'didMoveToSuperview()', a nie 'drawRect()' –