CALayer - backgroundColor flipped?

徘徊边缘 提交于 2019-12-10 20:25:39

问题


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.


回答1:


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




回答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.




回答3:


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.



来源:https://stackoverflow.com/questions/5604531/calayer-backgroundcolor-flipped

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!