Mostafa Sultan
Mostafa Sultan

Reputation: 2438

Draw on UIImageView without replacing its original image iOS

This code make changes to the imageview, but it replaces its original image. I need to edit on the original image not to replace it.

- (void)drawShapes {
    //NSLog(@"In drawShapes!");

    UIGraphicsBeginImageContext(self.planView.frame.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    for(myShape *i in _collection) {
        [self drawShapesSubroutine:i contextRef:context];
        if(i.selected == true) {
            CGContextSetLineWidth(context, 1.0f);
            CGContextSetStrokeColorWithColor(context, [[UIColor darkGrayColor] CGColor]);
            float num[] = {6.0, 6.0};
            CGContextSetLineDash(context, 0.0, num, 2);

            CGRect rectangle;
            [self drawShapeSelector:i selectorRect: &rectangle];
            CGContextAddRect(context, rectangle);
            CGContextStrokePath(context);


            //tapped = true;
        }
    }

    if(!skipDrawingCurrentShape && (selectedIndex == -1)) {
        [self drawShapesSubroutine:_currentShape contextRef:context];
    }
    self.planView.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
}

When I remove this line:

self.planView.image = UIGraphicsGetImageFromCurrentImageContext();

The image doesn't disappear but also doesn't draw. I need to draw without removing the original photo.

Upvotes: 0

Views: 484

Answers (1)

Teja Nandamuri
Teja Nandamuri

Reputation: 11201

You cant do imagview.image because, it will replace the old image with new one. If you are planning to draw something new on the image view, try to add sublayer on the imageview.

convert your image into cgiimage and add it to layer.you should convert UIGraphicsGetImageFromCurrentImageContext() into UIGraphicsGetImageFromCurrentImageContext().CGImage

you need to create a CALayer and add your CGI image to the layer.contents and use that layer as sub layer

CALayer *layer = [CALayer layer];
layer.contents = (id)UIGraphicsGetImageFromCurrentImageContext().CGImage;

and do this:

[self.imageView.layer addSublayer:layer];

Upvotes: 6

Related Questions