ios - Swift - Using CGContext to draw with finger -
i'm trying make drawing app. have single custom uiview:
class drawview: uiview { var touch : uitouch! var lastpoint : cgpoint! var currentpoint : cgpoint! override func touchesbegan(touches: set<nsobject>, withevent event: uievent) { touch = touches.first as! uitouch lastpoint = touch.locationinview(self) println(lastpoint) } override func touchesmoved(touches: set<nsobject>, withevent event: uievent) { touch = touches.first as! uitouch currentpoint = touch.locationinview(self) self.setneedsdisplay() lastpoint = currentpoint } override func drawrect(rect: cgrect) { var context = uigraphicsgetcurrentcontext() cgcontextsetlinewidth(context, 5) cgcontextsetstrokecolorwithcolor(context, uicolor.bluecolor().cgcolor) cgcontextsetlinecap(context, kcglinecapround) cgcontextbeginpath(context) if lastpoint != nil { cgcontextmovetopoint(context, lastpoint.x, lastpoint.y) cgcontextaddlinetopoint(context, currentpoint.x, currentpoint.y) } cgcontextstrokepath(context) } }
when run it, however, blue dot follows finger, no lines?
what doing wrong?
two things:
calling
self.setneedsdisplay
doesn't calldrawrect
. sets flagdrawrect
called in near future. since setlastpoint
currentpoint
right after that, whendrawrect
calledlastpoint
equalcurrentpoint
.drawrect
redraws entire view every time called, @ you'd ever see recent line. if fixed problem 1, you'd have short line following finger instead of dot. if want see whole trail, you'll need store points in array property of view, , draw lines connect of points indrawrect
.
Comments
Post a Comment