【问题标题】:Why can't I draw on an image when I subclass UIView?当我继承 UIView 时,为什么我不能在图像上绘图?
【发布时间】:2016-01-08 15:41:12
【问题描述】:

我正在尝试使用this tutorial 中的代码从相机胶卷中绘制图像。从相机胶卷中选择一张照片后,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)
}

}

【问题讨论】:

  • 自己没有尝试:至少在draw()中将tempImageView的frame origin设置为(0,0)(即不要使用parents bounds不变),并设置在drawRect()中描边路径之前的lineWidth

标签: ios swift uiview uiimageview uipangesturerecognizer


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-28
    • 2013-07-21
    • 2010-09-28
    • 1970-01-01
    • 2015-10-07
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    相关资源
    最近更新 更多