add subLayer to a imageView.layer

12,055

Solution 1

Try this:

[outputImage.layer insertSublayer:shapeLayer atIndex:0];

Solution 2

I solved similar problem by using UIView below UIImageView and setting a layer to UIView. When you add a layer to UIImageView at index 0, your image will not be visible.

I have a UIView called photoView. It has a subview of class UIImageView, that has same bounds and has a clear background color. And I add a gradientLayer to photoView.

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Adding gradient background to UIImageView
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = self.photoImageView.bounds;
    gradientLayer.colors = @[(id)[UIColor customUltraLightGrayColor].CGColor, (id)[UIColor customUltraLightGrayColor].CGColor, (id)[UIColor customDarkGrayColor].CGColor];
    gradientLayer.locations = @[@(0.0), @(0.6)];
    [self.photoView.layer insertSublayer:gradientLayer atIndex:0];
}

As a result I get this:

Gradient background of UIImageView

Share:
12,055
jean bernard
Author by

jean bernard

Updated on June 04, 2022

Comments

  • jean bernard
    jean bernard almost 2 years

    well I know that every imageViews have a layer (we can access it with :imageView.layer).I would like to use the layer of my imageView and add a subLayer to it's layer:shapeLayer(that is a CAShapeLayer) My code doesn't work, it doesn't show the shape layer!

    - (void)viewDidLoad 
    {
       imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
       [self.view addSubview:imageView];
    }
    
    - (void)anotherMethod
    {
       [imageView.layer addSublayer:shapeLayer];
    }
    

    How can I solve this please ?