-2

I'm trying to copy from image 1 to image 2 pixel by pixel, and I save the data from the image 1 in dictionary: [UIColor:CGPoint].

How to draw on CGContext all points pixel by pixel with the exact color for certain pixel on the image 2 at the same CGPoint?

@IBAction func save(sender: UIButton) {
    UIGraphicsBeginImageContext(CGSizeMake(100, 50))
    let context = UIGraphicsGetCurrentContext()
    for (color,point) in dict{
        drawPixel(context!, startPoint: point, color: color.CGColor)
    }
    testIV.image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
}

func drawPixel(context:CGContextRef, startPoint:CGPoint, color:CGColorRef){
    dispatch_async(dispatch_get_main_queue(), {
    CGContextSaveGState(context)
    CGContextSetLineCap(context, .Square)
    CGContextBeginPath(context)
    CGContextSetStrokeColorWithColor(context, color)
    CGContextSetLineWidth(context, 1.0)
    CGContextMoveToPoint(context, startPoint.x + 0.5, startPoint.y + 0.5)
    CGContextAddLineToPoint(context, startPoint.x + 0.5, startPoint.y + 0.5)
    CGContextStrokePath(context)
    CGContextRestoreGState(context)
    })
}

I've tried like this but the image is empty...

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Bogdan Bogdanov
  • 882
  • 11
  • 36
  • 79

1 Answers1

0

Remove the call to dispatch_async. You want your drawing code to run immediately, but dispatch_async causes it to run later on, long after the rest of your save method has finished.

func drawPixel(context:CGContextRef, startPoint:CGPoint, color:CGColorRef){
    CGContextSaveGState(context)
    CGContextSetLineCap(context, .Square)
    CGContextBeginPath(context)
    CGContextSetStrokeColorWithColor(context, color)
    CGContextSetLineWidth(context, 1.0)
    CGContextMoveToPoint(context, startPoint.x + 0.5, startPoint.y + 0.5)
    CGContextAddLineToPoint(context, startPoint.x + 0.5, startPoint.y + 0.5)
    CGContextStrokePath(context)
    CGContextRestoreGState(context)
}

(This is also a really inefficient way to do things, but you'll figure that out soon enough...)

Kurt Revis
  • 27,695
  • 5
  • 68
  • 74