3

I'm creating a CALayer like this:

UIColor *color = [UIColor colorWithPatternImage:[UIImage imageNamed:@"MyPattern.png"]];
backgroundLayer = [[CALayer alloc] init];
[backgroundLayer setBackgroundColor:[color CGColor]];
[[self layer] addSublayer:backgroundLayer];

For some reason, the pattern is drawn upside down. I've already tried setting geometryFlipped and applying sublayer transforms, but it doesn't work.

ryyst
  • 9,563
  • 18
  • 70
  • 97

3 Answers3

11

Using [backgroundLayer setTransform:CATransform3DMakeScale(1.0, -1.0, 1.0)]; actually does work.

ryyst
  • 9,563
  • 18
  • 70
  • 97
2

I would rather use this method:

CALayer *backgroundLayer = [CALayer layer];

backgroundLayer.frame = CGRectMake(50, 50, 200, 200);

UIImage *img = [UIImage imageNamed:@"MyPattern.png"];

CGImageRef imgRef = CGImageRetain(img.CGImage);


backgroundLayer.contents = (id) imgRef;


[self.layer addSublayer:backgroundLayer];

This will provide image content inside the layer and it fits automatically, so it works great for backgrounds. Im not sure why your method isnt working, sorry about that, but I thought it would be nice to provide you with this method.

1

Instead of using CATransform3DMakeScale you can flip image yourself:

UIImage* img = [UIImage imageNamed:@"MyPattern.png"];
img = [UIImage imageWithCGImage:img.CGImage
                          scale:img.scale 
                    orientation:UIImageOrientationDownMirrored];
UIColor* color = [UIColor colorWithPatternImage:img];
…

This works fine for me.

Or you can go further and actually redraw the image.

- (UIImage*)flipImage:(UIImage*)image {
    UIGraphicsBeginImageContext(image.size);
    CGContextDrawImage(UIGraphicsGetCurrentContext(),CGRectMake(0.,0., image.size.width, image.size.height),image.CGImage);
    UIImage* img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

Details why it can be useful are in this answer.

Community
  • 1
  • 1
zxcat
  • 2,054
  • 3
  • 26
  • 40
  • The first method did not work, but the second worked. Anyone knows why? The first worked when i used the image in a UIImageView but. – Rakesha Shastri Aug 03 '21 at 05:20