GGKey GGKey - 1 year ago 132
iOS Question

Clear Image on UIImageView subview of a MapView and draw new Image

I draw a Gif image in a subview onto a Mapview. The Gif is not just rectangle. The new image will be rotated, so it's just not possible to draw the new image over the old. I need to clear the old image before draw the new. I can't find any solution to do this. This is my working code so far:

CALayer *layer = [CALayer layer];
layer.bounds = CGRectMake(0, 0, 260, 260);
CGPoint center = CGPointMake(150, 300);
layer.position = center;
layer.contents = (id) [UIImage imageNamed:@"Image.gif"].CGImage;
layer.affineTransform = CGAffineTransformMakeRotation(angleDegree * 3.14/180);
[[mapView layer] addSublayer:layer];

Answer Source

Remove the layer from mapView. Make sure you hold the reference to layer which loads the image.

[layer removeFromSuperlayer];


As you haven't provided me with much code I'll try my best provide solution as per my understanding of your situation buddy :)

- (IBAction)selectTime:(id)sender {

    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
    [outputFormatter setDateFormat:@"HH"];
    NSString *eventHours = [outputFormatter];
    currentHour = [eventHours floatValue];

    //some calculations

    if (self.imageLayer != nil) {
        //If image added earlier then this statement will remove it from superlayer which is your mapView
        [self.imageLayer removeFromSuperlayer];

    self.imageLayer = [CALayer layer];
    self.imageLayer.bounds = CGRectMake(0, 0, 260, 260);
    CGPoint center = CGPointMake(150, 300);
    self.imageLayer.position = center;
    self.imageLayer.contents = (id) [UIImage imageNamed:@"angle.gif"].CGImage;
    self.imageLayer.affineTransform = CGAffineTransformMakeRotation(shadowDirection * 3.14/180);
    [[mapView layer] addSublayer:self.imageLayer];

As you can see I am accessing the same CALyer that I had used to add image to MapView. In order to be able to persist that I have created a property called imageLayer in my .m file.

You should ask the layer to remove itself from super layer to remove it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download