Question

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.

Was it helpful?

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;

OTHER TIPS

The line

UIImage *artworkImage = [artwork imageWithSize: cell.imageView.bounds.size];

creates an image with the size of the cell. So, it's scaled in this line and the image won't be bigger than the cell and therefore it will not scale afterwards.

I would leave the image at it's original size or at a size 2x the cell size and leave the scaling up to contentMode.

CGSize newSize = CGSizeMake(artwork.bounds.size.width, artwork.bounds.size.height)
UIImage *artworkImage = [artwork imageWithSize: newSize];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top