缩放CAShapeLayer时出现意外行为

时间:2018-02-18 16:40:04

标签: ios swift cgaffinetransform cashapelayer uipinchgesturerecognizer

我使用以下代码来缩放CAShapelayer实例(即self.view.layer.sublayers![0]):

class ViewController: UIViewController {   
override func viewDidLoad()
{
    super.viewDidLoad()
    self.view = Map(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height))
    let pinchGR = UIPinchGestureRecognizer(target: self, action: #selector(self.didPinch(_:)))
    self.view.addGestureRecognizer(pinchGR)
}

@objc func didPinch(_ pinchGR: UIPinchGestureRecognizer)
{
    let transformation = CGAffineTransform(a: pinchGR.scale, b: 0, c: 0, d: pinchGR.scale, tx: 0, ty: 0)
    if pinchGR.state == .began || pinchGR.state == .changed
    {
        self.view.layer.sublayers![0].setAffineTransform(transformation)
    }
}}

class Map: UIView{
override init(frame: CGRect)
{
    super.init(frame: frame)
    self.backgroundColor = UIColor.blue
    drawTestShape()
}
required init?(coder aDecoder: NSCoder)
{
    super.init(coder: aDecoder)
}
func drawTestShape()
{
    let shapeLayer = CAShapeLayer()
    shapeLayer.frame = self.frame
    let path = UIBezierPath()
    shapeLayer.lineWidth = 5.0
    shapeLayer.fillColor = nil
    shapeLayer.strokeColor = UIColor.white.cgColor
    shapeLayer.backgroundColor = UIColor.red.cgColor
    path.move(to: CGPoint(x:200,y:200))
    path.addLine(to: CGPoint(x:300,y:300))
    path.addLine(to: CGPoint(x:100,y:300))
    path.close()
    shapeLayer.path = path.cgPath
    self.layer.addSublayer(shapeLayer)
}}

在第一个捏合手势中正确执行缩放。但是,当应用第二个捏合手势时,CAShapelayer实例将从其初始大小再次启动,而不是从第一个手势后的大小开始。

1 个答案:

答案 0 :(得分:0)

我无法真正落后于扩展图层的想法,但如果必须这样做,请尝试更像这样的内容;这是实现捏手势识别器的标准模式,所以最好坚持下去:

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    return UITableViewAutomaticDimension
}