简体   繁体   中英

Place a full sized image to fit the entire screen in a CALayer

I have an image (png) which must fill the entire screen of my app. I'm using CALayers and doing everything programatically but still this sounds like something that should be trivial to but I can't get it to work. I have two versions of the image a retina version (2048px x 1536px) and a non-retina version 1024px x 768px). The image is listed a universal image in the Asset catalogue

The code is simple enough I think:

// CREATE FULL SCREEN CALAYER  
CALayer *myLayer = [[CALayer alloc] init];
[myLayer setBounds:CGRectMake(0, 0, bounds.size.width, bounds.size.height)]; 
[myLayer setPosition:CGPointMake(bounds.size.width/2, bounds.size.height/2)];
[self.view.layer addSublayer:myLayer];

// LOAD THE IMAGE INTO THE LAYER —— AM EXPECTING IT TO FILL THE LAYER
UIImage *layerImage = [UIImage imageNamed:@"infoScreen"];
CGImageRef image = [layerImage CGImage];
[myLayer setContents:(__bridge id)image];
[myLayer setContentsGravity:kCAGravityCenter]; /* IT WORKS FINE IF I USE setContentsGravity:kCAGravityResizeAspectFill */

This code works fine on a non-iPad retina. However on the Retina iPad, the image is always loaded at twice the actual size (so it appears zoomed in). I'm using the Simulator and iOS 8. What am I doing wrong?

Beging your image processing with func UIGraphicsBeginImageContextWithOptions(size: CGSize, opaque: Bool, scale: CGFloat)

The last parameter in the above function determines the scaling for the graphics. You can set this value by retrieving the scale property of the main screen. In swift I would do it this way: var screen = UIScreen.mainScreen() var scale = screen.scale

Hope it helps.

Edit: - Code for doing this in swift, you can modify it to suit your need.

    UIGraphicsBeginImageContextWithOptions(rect.size, true, 0.0)
    var ctx : CGContextRef = UIGraphicsGetCurrentContext()
    <UIImage>.drawInRect(rect)

I had this same problem, was solved by setting the contentsScale value on the CALayer - for some reason the default scale on CALayers is always 1.0, even on Retina devices.

ie

layer.contentsScale = [UIScreen mainScreen].scale;

Also, if you're drawing a shape using CAShapeLayer and wondering its edges look a little jagged on retina devices, try:

shapeLayer.rasterizationScale = [UIScreen mainScreen].scale;
shapeLayer.shouldRasterize = YES;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM