Introduction
For any media app, it is needed to bring some information about the playback with a correctly scaled image in the lock screen of iOS devices to enrich the user experience.
Background
I needed this feature, but didn't find a clean solution on the internet. So I figured it out and now want to share my knowledge.
Using the Code
It is the straight use of the MPNowPlayingInfoCenter
API from Apple with the trick to get the image centered and scaled into a quadratic taget image.
- (void)refreshNowPlayingInfo:(UIImage*) image
{
NSMutableDictionary *info = [NSMutableDictionary dictionary];
[info setObject:@"Artist" forKey:MPMediaItemPropertyArtist];
if (image) {
const CGFloat SIZE = 128*8;
CGSize size = image.size;
CGFloat x = size.width;
CGFloat y = size.height;
if( x > y ) {
y = (y * SIZE) / x;
x = SIZE;
} else if( x < y )
{
x = (x * SIZE) / y;
y = SIZE;
} else {
x = SIZE;
y = SIZE;
}
UIGraphicsBeginImageContext( CGSizeMake(SIZE, SIZE) );
[image drawInRect:CGRectMake( (SIZE-x)/2, (SIZE-y)/2, x, y)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[info setObject:[[MPMediaItemArtwork alloc] initWithImage:newImage]
forKey:MPMediaItemPropertyArtwork];
}
[MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = info;
}
Points of Interest
Interesting to see how easy the MPNowPlayingInfoCenter
API works, but why do I have to center and scale the picture myself. For further information, Apple has provided the MPNowPlayingInfoCenter documentation.
History
- 12/8/2016: Initial version