Search code examples
uiimageuicollectionviewuicollectionviewcelltvos

tvOS adjustsImageWhenAncestorFocused crops image collection view cell


When you use .imageView.adjustsImageWhenAncestorFocused you get your image scaled, you get it bigger on focus. The image goes beyond it's bounds. That means that you can't see full image - it's coped on all sides.

You have:

enter image description here

You want:

enter image description here


Solution

  • If you want it work from the box, you need to remember to reserve Focused/Safe zone size (from documentation) when you create your image.

    In my case I have my images from server and I can't edit them. What worked for me - it's to redraw image right before setting:

        UIImage *oldImage = [UIImage imageNamed:@"example"];
        CGFloat width = cell.imageView.frame.size.width;
        CGFloat height = cell.imageView.frame.size.height;
        CGSize newSize = CGSizeMake(width, height);
        CGRect newRect = CGRectIntegral(CGRectMake(0, 0, newSize.width, newSize.height));
        CGImageRef imageRef = oldImage.CGImage;
    
        UIGraphicsBeginImageContextWithOptions(newSize, NO, 0);
        CGContextRef resizeContext = UIGraphicsGetCurrentContext();
    
        CGContextSetInterpolationQuality(resizeContext, kCGInterpolationHigh);
        CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, newSize.height);
    
        CGContextConcatCTM(resizeContext, flipVertical);
        CGContextDrawImage(resizeContext, newRect, imageRef);
    
        CGImageRef newImageRef = CGBitmapContextCreateImage(resizeContext);
        UIImage *newImageResized = [UIImage imageWithCGImage:newImageRef];
    
        CGImageRelease(newImageRef);
        UIGraphicsEndImageContext();
        dispatch_async(dispatch_get_main_queue(), ^{
            cell.imageView.image = newImageResized;
        });
    

    It's nor necessary to redraw in this way, but the point is you need to draw your UIImage again in order to have your image displayed properly.

    Code from here.