为什么我在子类 UIView 时不能在图像上绘图?



我正试图使用本教程中的代码在相机胶卷上绘制图像。从相机胶卷中选择照片后,imageView被设置为该照片。当用户按下绘制按钮时,tempImageView会添加到照片上,这样用户就可以在上面绘制。然而,当我试图在图像上绘制时,什么都没有发生。为什么?

代码:

class EditViewController: UIViewController{
    var tempImageView: DrawableView!
    var imageView: UIImageView = UIImageView(image: UIImage(named: "ClearImage"))
    func draw(sender: UIButton!) {
        tempImageView = DrawableView(frame: imageView.bounds)
        tempImageView.backgroundColor = UIColor.clearColor()
        self.view.addSubview(tempImageView)
    }
}
class DrawableView: UIView {
let path=UIBezierPath()
var previousPoint:CGPoint
var lineWidth:CGFloat=10.0
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override init(frame: CGRect) {
    previousPoint=CGPoint.zero
    super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
    previousPoint=CGPoint.zero
    super.init(coder: aDecoder)
    let panGestureRecognizer=UIPanGestureRecognizer(target: self, action: "pan:")
    panGestureRecognizer.maximumNumberOfTouches=1
    self.addGestureRecognizer(panGestureRecognizer)
}
override func drawRect(rect: CGRect) {
    // Drawing code
    UIColor.greenColor().setStroke()
    path.stroke()
    path.lineWidth=lineWidth
}
func pan(panGestureRecognizer:UIPanGestureRecognizer)->Void
{
    let currentPoint=panGestureRecognizer.locationInView(self)
    let midPoint=self.midPoint(previousPoint, p1: currentPoint)
    if panGestureRecognizer.state == .Began
    {
        path.moveToPoint(currentPoint)
    }
    else if panGestureRecognizer.state == .Changed
    {
        path.addQuadCurveToPoint(midPoint,controlPoint: previousPoint)
    }
    previousPoint=currentPoint
    self.setNeedsDisplay()
}
func midPoint(p0:CGPoint,p1:CGPoint)->CGPoint
{
    let x=(p0.x+p1.x)/2
    let y=(p0.y+p1.y)/2
    return CGPoint(x: x, y: y)
}
}

确保tempImageView.userIteractionEnabled=YES。默认情况下,UIImageView的此属性为NO。在给gestureRecogniser方法设置断点后,看看是否正在调用它。

最新更新