ioscocoa-touchuitableviewmpmediaitemartwork

How to set MediaItemArtwork Image Fill in UITableViewCell in iOS?


I am trying to enter MPMediaItemArtwork Image into UITableView's cell's ImageView with following code.

MPMediaItemArtwork *artwork = [[[self.arrayOfAlbums objectAtIndex:indexPath.row] representativeItem]valueForProperty:MPMediaItemPropertyArtwork];
    UIImage *artworkImage = [artwork imageWithSize: cell.imageView.bounds.size];

if (artworkImage)
    {
        cell.imageView.image = artworkImage;

    }

    else
    {
        cell.imageView.image = [UIImage imageNamed: @"noArtwork.png"];
    }

It's okay when i insert Artwork image in UITableView's cell ImageView.

But when my artwork image is too small or big , it's happened like following pic. Not in completely fill in cell's ImageView.

enter image description here

You see that? I want to set Fill with Stretch like iOS Music App

Here is Build-in App Artwork Image that set Completely fill with Stretch

enter image description here

I want to do like that.

So i used cell.imageView.contentMode = UIViewContentModeScaleAspectFill; however it's not effect.

So how can i do that? Thanks you for your work.


Solution

  • Try this for calculating a new and fitting image; Adjust newRect to the rect of your cell.

    // scale and center the image
    
    CGSize sourceImageSize = [artworkImage size];
    
    // The rectangle of the new image
    CGRect newRect;
    newRect = CGRectMake(0, 0, 40, 33);
    
    // Figure out a scaling ratio to make sure we maintain the same aspect ratio
    float ratio = MAX(newRect.size.width / sourceImageSize.width, newRect.size.height / sourceImageSize.height);
    
    UIGraphicsBeginImageContextWithOptions(newRect.size, NO, 1.0);
    
    // Center the image in the thumbnail rectangle
    CGRect projectRect;
    projectRect.size.width = ratio * sourceImageSize.width;
    projectRect.size.height = ratio * sourceImageSize.height;
    projectRect.origin.x = (newRect.size.width - projectRect.size.width) / 2.0;
    projectRect.origin.y = (newRect.size.height - projectRect.size.height) / 2.0;
    
    [sourceImage drawInRect:projectRect];
    UIImage *sizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    cell.imageView.image = sizedImage;