Drawing lines with core graphics - ios

I want to draw more than one straight line in core graphics. or save the line and start a new one. I used two variables for touch location and assigned touch location to them in touch Began,Moved,Ended then I used this:
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
context?.setStrokeColor(UIColor(red: 0, green: 0, blue: 0, alpha: 1.0).cgColor)
context?.setLineWidth(5.0)
context?.move(to: CGPoint(x: firstTouchLocation.x, y: firstTouchLocation.y))
context?.addLine(to: CGPoint(x: lastTouchLocation.x, y: lastTouchLocation.y))
context?.strokePath()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
firstTouchLocation = touch.location(in: self)
lastTouchLocation = firstTouchLocation
setNeedsDisplay()
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
lastTouchLocation = touch.location(in: self)
setNeedsDisplay()
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
lastTouchLocation = touch.location(in: self)
setNeedsDisplay()
}
}

Try drawing the line using CAShapeLayer like so:
func addLine(fromPoint start: CGPoint, toPoint end:CGPoint) {
let line = CAShapeLayer()
let linePath = UIBezierPath()
linePath.move(to: start)
linePath.addLine(to: end)
line.path = linePath.cgPath
line.strokeColor = UIColor.red.cgColor
line.lineWidth = 1
line.lineJoin = kCALineJoinRound
self.view.layer.addSublayer(line)
}
Hope this helps!

You got to have a model object which represent a line say ex: LineAnnotation. LineAnnotation will hold start and end points, color and many others details about the line. Hold every LineAnnotation(line) in an array. Iterate through this array and draw line one by one. In your case are drawing using latest data. Previous points which are drawn will e refreshed when you call setNeedsDisplay()

As per apples documentation(https://developer.apple.com/documentation/uikit/uiview/1622437-setneedsdisplay) setNeedsDisplay method redraws your view, so you are left with fresh view with latest line only.
To solve your problem simply pull your code in a method and call that method whenever you made a touch.
override func draw(_ rect: CGRect) {
drawLine()
}
func drawLine()
{
let context = UIGraphicsGetCurrentContext()
context?.setStrokeColor(UIColor(red: 0, green: 0, blue: 0, alpha: 1.0).cgColor)
context?.setLineWidth(5.0)
context?.move(to: CGPoint(x: firstTouchLocation.x, y: firstTouchLocation.y))
context?.addLine(to: CGPoint(x: lastTouchLocation.x, y: lastTouchLocation.y))
context?.strokePath()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
firstTouchLocation = touch.location(in: self)
lastTouchLocation = firstTouchLocation
drawLine()
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
lastTouchLocation = touch.location(in: self)
drawLine()
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
lastTouchLocation = touch.location(in: self)
drawLine()
}
}

Related

Moving a Sprite along a UIBezierPath

I have been having some trouble moving a Sprite along a UIBezierPath. I am getting this path from my view controller and it is passing along the correct path. Any ideas on why this isn't animating? Eventually I want to be able to move multiple sprites along different bezier paths.
func play(){
let img = SKSpriteNode(imageNamed:"ball.png")
img.position = CGPoint(x: self.frame.size.width/4, y: self.frame.size.height/4)
self.addChild(img)
new_path = viewController.path //UIBezierPath is being returned
let followPath = SKAction.follow(new_path.cgPath, asOffset: true, orientToPath: false, duration: 5.0)
img.run(followPath)
}
I am trying to draw a bezier path here(Kind of like a whiteboard app)in a custom view and then access the bezier path when I want to animate it. The path seems to be passed through correctly.
private var path: UIBezierPath!
let newpath = UIBezierPath()
func initBezierPath() {
path = UIBezierPath()
path.lineCapStyle = CGLineCap.round
path.lineJoinStyle = CGLineJoin.round
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch: AnyObject? = touches.first
lastPoint = touch!.location(in: self)
pointCounter = 0
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch: AnyObject? = touches.first
let newPoint = touch!.location(in: self)
path.move(to: lastPoint)
path.addLine(to: newPoint)
lastPoint = newPoint
pointCounter += 1
if pointCounter == pointLimit {
pointCounter = 0
renderToImage()
setNeedsDisplay()
newpath.append(path)
path.removeAllPoints()
}
else {
setNeedsDisplay()
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
pointCounter = 0
renderToImage()
setNeedsDisplay()
newpath.append(path)
path.removeAllPoints()
}

Swift 3/SpriteKit - Draw independent shapes with finger

I'm a beginner following the tutorial here for drawing shapes in Swift.
import SpriteKit
class GameScene: SKScene {
var activeSlice: SKShapeNode!
var activeSlicePoints = [CGPoint]()
override func didMove(to view: SKView) {
createSlices()
}
func createSlices() {
activeSlice = SKShapeNode()
activeSlice.strokeColor = UIColor(red: 1, green: 0.9, blue: 0, alpha: 1)
activeSlice.lineWidth = 9
addChild(activeSlice)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
if let touch = touches.first {
let location = touch.location(in: self)
activeSlicePoints.append(location)
redrawActiveSlice()
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let location = touch.location(in: self)
activeSlicePoints.append(location)
redrawActiveSlice()
}
override func touchesEnded(_ touches: Set<UITouch>?, with event: UIEvent?) {
}
func redrawActiveSlice() {
let path = UIBezierPath()
path.move(to: activeSlicePoints[0])
for i in 1 ..< activeSlicePoints.count {
path.addLine(to: activeSlicePoints[i])
}
activeSlice.path = path.cgPath
}
}
With this code, when you release the finger then touch again to draw, you have a line connecting the two shapes.
I would like to draw independent shapes.
Perhaps by modifying the code so that for each instance of touchesEnded(), the array of points that represents the shape is stored in a multidimensional array, and by creating an array of points for each new instance of touchesBegan()?
Thank you for your help.
It's something like
override func touchesEnded(_ touches: Set<UITouch>?, with event: UIEvent?) {
createSlices()
}

Nodes in SKShapeNode reappearing when creating another new node

Im trying to write the code for a line that draws with the drag of a finger but deletes when the finger is removed (in SpriteKit and Swift 3)
var shapeNodes = [SKShapeNode]()
var pathToDraw = CGMutablePath()
var lineNode = SKShapeNode()
func deleteAllShapeNodes() {
for node in shapeNodes {
node.removeFromParent()
}
shapeNodes.removeAll(keepingCapacity: false)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch: AnyObject in touches {
firstPoint = touch.location(in: self)
}
shapeNodes.append(lineNode)
pathToDraw.move(to: CGPoint(x: firstPoint.x, y: firstPoint.y))
lineNode.lineWidth = 4
lineNode.strokeColor = UIColor.white
lineNode.name = "Line"
lineNode.zPosition = 100000
lineNode.path = pathToDraw
self.addChild(lineNode)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch: AnyObject in touches{
positionInScene = touch.location(in: self)
}
shapeNodes.append(lineNode)
pathToDraw.addLine(to: CGPoint(x: positionInScene.x, y: positionInScene.y))
lineNode.path = pathToDraw
firstPoint = positionInScene
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch: AnyObject in touches{
TouchEndPosition = touch.location(in: self)
}
self.deleteAllShapeNodes()
}
the first line draws and deletes perfectly but when i start drawing the second line the first line reappears.
Creating a brand-new CGMutablePath seems to be the only way to get an empty CGMutablePath.
And you are adding the only instance of SKShapeNode (kept in lineNode) into shapeNodes, it's non-sense. Your lineNode keeps all the lines you added to your pathToDraw.
Generally, you may need to learn when to instantiate objects, and when to release them.
Try this:
//### You are adding the same instance multiple times into this array, it's nonsense.
//var shapeNodes = [SKShapeNode]()
//### `pathToDraw` can be kept in the `SKShapeNode`.
//var pathToDraw = CGMutablePath()
//### In this case, this is not a good place to instantiate an `SKShapeNode`.
var lineNode: SKShapeNode?
func deleteAllShapeNodes() {
//### Release the `SKShapeNode` contained in `lineNode` to delete all lines.
lineNode?.removeFromParent()
lineNode = nil
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let firstPoint = touches.first!.location(in: self)
self.lineNode?.removeFromParent()
//### If you want somethings which live while dragging, `touchesBegan(_:with:)` is a good place to instantiate them.
let lineNode = SKShapeNode()
//### Create an empty new `CGMutablePath` at each `touchesBegan(_:with:)`.
let pathToDraw = CGMutablePath()
self.lineNode = lineNode
pathToDraw.move(to: firstPoint)
lineNode.lineWidth = 4
lineNode.strokeColor = UIColor.white
lineNode.name = "Line"
lineNode.zPosition = 100000
//### `pathToDraw` is kept in the `SKShapeNode`.
lineNode.path = pathToDraw
self.addChild(lineNode)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let positionInScene = touches.first!.location(in: self)
if let lineNode = self.lineNode {
//### Modify the `CGMutablePath` kept in the `SKShapeNode`.
let pathToDraw = lineNode.path as! CGMutablePath
pathToDraw.addLine(to: positionInScene)
//### Refresh the shape of the `SKShapeNode`.
lineNode.path = pathToDraw
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
self.deleteAllShapeNodes()
}

Removing lagging latency in drawing UIBezierPath smooth lines in Swift

The code below draws smooth curved lines by overriding touches, but there is noticeable lagging or latency. The code uses addCurveToPoint and calls setNeedsDisplay after every 4 touch points which causes a jumpy appearance as the drawing doesn't keep up with finger movements. To remove the lagging or perceived latency, touch points 1, 2, 3 (leading up to touch point 4) could be temporarily filled with addQuadCurveToPoint and addLineToPoint.
How can this actually be achieved in code to remove perceived lagging by using a temporary Line and QuadCurved line before displaying a final Curved line?
If the below class is attached to one UIView (e.g. viewOne or self), how do I make a copy of the drawing to another UIView outside the class (e.g. viewTwo) after touchesEnded?
// ViewController.swift
import UIKit
class drawSmoothCurvedLinesWithLagging: UIView {
let path=UIBezierPath()
var incrementalImage:UIImage?
var points = [CGPoint?](count: 5, repeatedValue: nil)
var counter:Int?
var strokeColor:UIColor?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func drawRect(rect: CGRect) {
autoreleasepool {
incrementalImage?.drawInRect(rect)
strokeColor = UIColor.blueColor()
strokeColor?.setStroke()
path.lineWidth = 20
path.lineCapStyle = CGLineCap.Round
path.stroke()
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
counter = 0
let touch: AnyObject? = touches.first
points[0] = touch!.locationInView(self)
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch: AnyObject? = touches.first
let point = touch!.locationInView(self)
counter = counter! + 1
points[counter!] = point
if counter == 2{
//use path.addLineToPoint ?
//use self.setNeedsDisplay() ?
}
if counter == 3{
//use path.addQuadCurveToPoint ?
//use self.setNeedsDisplay() ?
}
if counter == 4{
points[3]! = CGPointMake((points[2]!.x + points[4]!.x)/2.0, (points[2]!.y + points[4]!.y)/2.0)
path.moveToPoint(points[0]!)
path.addCurveToPoint(points[3]!, controlPoint1: points[1]!, controlPoint2: points[2]!)
self.setNeedsDisplay()
points[0]! = points[3]!
points[1]! = points[4]!
counter = 1
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.drawBitmap()
self.setNeedsDisplay()
path.removeAllPoints()
counter = 0
}
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
self.touchesEnded(touches!, withEvent: event)
}
func drawBitmap(){
UIGraphicsBeginImageContextWithOptions(self.bounds.size, true, 0.0)
strokeColor?.setStroke()
if((incrementalImage) == nil){
let rectPath:UIBezierPath = UIBezierPath(rect: self.bounds)
UIColor.whiteColor().setFill()
rectPath.fill()
}
incrementalImage?.drawAtPoint(CGPointZero)
path.stroke()
incrementalImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Yes, adding a curve every few points will give it a stuttering lag. So, yes, you can reduce this affect by adding a line to points[1], adding a quad curve to points[2] and adding a cubic curve to points[3].
As you said, make sure to add this to a separate path, though. So, in Swift 3/4:
class SmoothCurvedLinesView: UIView {
var strokeColor = UIColor.blue
var lineWidth: CGFloat = 20
var snapshotImage: UIImage?
private var path: UIBezierPath?
private var temporaryPath: UIBezierPath?
private var points = [CGPoint]()
override func draw(_ rect: CGRect) {
snapshotImage?.draw(in: rect)
strokeColor.setStroke()
path?.stroke()
temporaryPath?.stroke()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
points = [touch.location(in: self)]
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let point = touch.location(in: self)
points.append(point)
updatePaths()
setNeedsDisplay()
}
private func updatePaths() {
// update main path
while points.count > 4 {
points[3] = CGPoint(x: (points[2].x + points[4].x)/2.0, y: (points[2].y + points[4].y)/2.0)
if path == nil {
path = createPathStarting(at: points[0])
}
path?.addCurve(to: points[3], controlPoint1: points[1], controlPoint2: points[2])
points.removeFirst(3)
temporaryPath = nil
}
// build temporary path up to last touch point
if points.count == 2 {
temporaryPath = createPathStarting(at: points[0])
temporaryPath?.addLine(to: points[1])
} else if points.count == 3 {
temporaryPath = createPathStarting(at: points[0])
temporaryPath?.addQuadCurve(to: points[2], controlPoint: points[1])
} else if points.count == 4 {
temporaryPath = createPathStarting(at: points[0])
temporaryPath?.addCurve(to: points[3], controlPoint1: points[1], controlPoint2: points[2])
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
finishPath()
}
override func touchesCancelled(_ touches: Set<UITouch>?, with event: UIEvent?) {
finishPath()
}
private func finishPath() {
constructIncrementalImage()
path = nil
setNeedsDisplay()
}
private func createPathStarting(at point: CGPoint) -> UIBezierPath {
let localPath = UIBezierPath()
localPath.move(to: point)
localPath.lineWidth = lineWidth
localPath.lineCapStyle = .round
localPath.lineJoinStyle = .round
return localPath
}
private func constructIncrementalImage() {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0.0)
strokeColor.setStroke()
snapshotImage?.draw(at: .zero)
path?.stroke()
temporaryPath?.stroke()
snapshotImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
}
You could even marry this with iOS 9 predictive touches (as I described in my other answer), which could reduce lag even further.
To take this resulting image and use it elsewhere, you can just grab the incrementalImage (which I renamed to snapshotImage, above), and drop it into an image view of the other view.
For Swift 2 rendition, see previous revision of this answer.

Swift - Using CGContext to draw with finger

I'm trying to make a drawing app. I have a 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 I run it, however, all I get is a blue dot that follows my finger, but no lines?
What am I doing wrong?
Hi i make some simple changes and fixed your code, hope it helps someone in the future (code it's updated for Swift 3) :
class DrawView: UIView {
var touch : UITouch!
var lineArray : [[CGPoint]] = [[CGPoint]()]
var index = -1
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
touch = touches.first! as UITouch
let lastPoint = touch.location(in: self)
index += 1
lineArray.append([CGPoint]())
lineArray[index].append(lastPoint)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
touch = touches.first! as UITouch
let currentPoint = touch.location(in: self)
self.setNeedsDisplay()
lineArray[index].append(currentPoint)
}
override func draw(_ rect: CGRect) {
if(index >= 0){
let context = UIGraphicsGetCurrentContext()
context!.setLineWidth(5)
context!.setStrokeColor((UIColor(red:0.00, green:0.38, blue:0.83, alpha:1.0)).cgColor)
context!.setLineCap(.round)
var j = 0
while( j <= index ){
context!.beginPath()
var i = 0
context?.move(to: lineArray[j][0])
while(i < lineArray[j].count){
context?.addLine(to: lineArray[j][i])
i += 1
}
context!.strokePath()
j += 1
}
}
}
}
Two things:
Calling self.setNeedsDisplay doesn't immediately call drawRect. It just sets a flag so that drawRect will be called in the near future. Since you set lastPoint to currentPoint right after that, when drawRect is called lastPoint is always equal to currentPoint.
drawRect redraws the entire view every time it is called, so at most you'd only ever see the most recent line. If you fixed problem 1, you'd have a short line following your finger instead of a dot. If you want to see the whole trail, you'll need to store the points in an array that is a property of your view, and then draw lines to connect all of the points in drawRect.
marcomoreira92 and Keuha's version worked for me, but I don't like to use indices that much. Thus here is an alternative version, which was tested in Swift 4.2:
class DrawView: UIView {
var lineArray: [[CGPoint]] = [[CGPoint]]()
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let firstPoint = touch.location(in: self)
lineArray.append([CGPoint]())
lineArray[lineArray.count - 1].append(firstPoint)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let currentPoint = touch.location(in: self)
lineArray[lineArray.count - 1].append(currentPoint)
setNeedsDisplay()
}
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
context?.setLineWidth(5)
context?.setStrokeColor(UIColor.black.cgColor)
context?.setLineCap(.round)
for line in lineArray {
guard let firstPoint = line.first else { continue }
context?.beginPath()
context?.move(to: firstPoint)
for point in line.dropFirst() {
context?.addLine(to: point)
}
context?.strokePath()
}
}
}

Resources