Tags

, , , , , ,

How to draw single line into UIImage using Core Graphics framework? Recently I needed this, so here is code ( everything is straightforward -> no explanation is needed 🙂 ):

    NSLog(@"Creating image");

    CGSize size = CGSizeMake(240.0f, 240.0f);
    UIGraphicsBeginImageContext(size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetStrokeColorWithColor(context, [[UIColor blackColor] CGColor]);
    CGContextSetFillColorWithColor(context, [[UIColor whiteColor] CGColor]);

    CGContextFillRect(context, CGRectMake(0.0f, 0.0f, 240.0f, 240.0f));

    CGContextSetLineWidth(context, 5.0f);
    CGContextMoveToPoint(context, 100.0f, 100.0f);
    CGContextAddLineToPoint(context, 150.0f, 150.0f);
    CGContextStrokePath(context);

    UIImage* result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    imageView.image = result;
    [imageView setNeedsDisplay];

    NSLog(@"Image creation finished");

Example can be found on my GitHub

Best