A few months ago I answered this question from Taimur Ajmal on StackOverflow. Taimur needed to locally resize the images presented in the Top Shelf Extension of his tvOS app.
As he pointed out,
TVContentItem has an
imageURL property, that is of
NSURL type, but there isn’t any kind of
In these cases you need to find a workaround in order to achieve the result asked by Taimur. I thought: since
imageURL is an URL, I could download it locally, modify the downloaded image with tools (like Core Graphics or other libraries) and present it. And it works like a charm!
So, these are the steps I followed:
- grabbing the
- creating a new image context with the size of the top shelf image
- saving it into the
- setting the local image URL as
- Let’s create our
Swift12let identifier = TVContentIdentifier(identifier: "myPicture", container: wrapperID)!let contentItem = TVContentItem(contentIdentifier: identifier )!
- Set the
Swift1contentItem.imageShape = .HDTV
- Grab the image from Internet. Actually I did this synchronously, you can also try to use other async methods to get that (
NSURLConnection, Alamofire, etc…):
Swift1let data : NSData = NSData(contentsOfURL: NSURL(string: "YOUR-URL-HERE")!)!
- Prepare the path where your image will be saved and get your
Swift1234let filename = "picture-test.jpg"let paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)let filepath = paths.first! + "/" + filenamelet img : UIImage = UIImage(data: data)!
- Assuming you’ve already set the
topShelfStyleproperty, get the size of the top shelf image with the method
TVTopShelfImageSizeForShape. This will be the size of your image context:
Swift1let shapeSize : CGSize = TVTopShelfImageSizeForShape(contentItem.imageShape, self.topShelfStyle)
- Create your image context of
shapeSizesize and draw the downloaded image into the context rect. Here you can do all your modifications to the image to adjust it into the desired size. In this example I took a square image from Instagram and I put white letterbox bands on the right and left sides.
Swift12345UIGraphicsBeginImageContext(shapeSize)let imageShapeInRect : CGRect = CGRectMake((shapeSize.width-shapeSize.height)/2,0,shapeSize.height,shapeSize.height)img.drawInRect(imageShapeInRect)let newImage = UIGraphicsGetImageFromCurrentImageContext()UIGraphicsEndImageContext()
- In the end, save this image into your
NSCacheDirectoryand set the image path as
Swift12UIImageJPEGRepresentation(newImage, 0.8)!.writeToFile(filepath, atomically: true)contentItem.imageURL = NSURL(fileURLWithPath: filepath)
- Complete your
TVContentItemwith other details (like title, internal link, etc…), run the top shelf extension… et voilà!
📝 License: CC BY-SA 3.0 with attribution required. Link to this post.
📷 Article: © Apple (source: apple.com). Screenshots: self-made