Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile / iOS

How to Fine Tune the Multimedia Controls

5.00/5 (3 votes)
8 Dec 2016CPOL 13.8K  
Show correct image in the now-playing information with the MPNowPlayingInfoCenter API.

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.

Objective-C
- (void)refreshNowPlayingInfo:(UIImage*) image
{
    NSMutableDictionary *info = [NSMutableDictionary dictionary];
    // add some information
    [info setObject:@"Artist" forKey:MPMediaItemPropertyArtist];

    if (image) {
		const CGFloat SIZE = 128*8;//could be other value
		CGSize size = image.size;
		CGFloat x = size.width;
		CGFloat y = size.height;
        //ensure proper scaling
		if( x > y )	{
			y = (y * SIZE) / x;
			x = SIZE;
		} else if( x < y )
		{
			x = (x * SIZE) / y;
			y = SIZE;
		} else {
			x = SIZE;
			y = SIZE;
		}
        //create a new image
		UIGraphicsBeginImageContext( CGSizeMake(SIZE, SIZE) );//full size
        //draw so, that it got centered in x and y
		[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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)