1
MPMediaItemArtwork *albumArt = [[MPMediaItemArtwork alloc] initWithImage:image]];

I have an UIImage which is rectangle, It's cropped to square when I put it to MPNowPlayingInfoCenter using MPMediaItemArtwork. How can I resize an UIImage to fit a square UIImage by width and leave the rest in blank?

enter image description here

Community
  • 1
  • 1
Jared Chu
  • 2,757
  • 4
  • 27
  • 38

1 Answers1

2

put UIImage into an UIImageView, set contentMode for UIImageView is UIViewContentModeScaleAspectFit and render it back to UIImage.

+ (UIImage *)imageToSquare:(UIImage *)image byWidth:(float)width{
        UIImageView *view = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, width, width)];
        [view setImage:image];
        view.contentMode = UIViewContentModeScaleAspectFit;

        UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
        [view.layer renderInContext:UIGraphicsGetCurrentContext()];

        UIImage * img = UIGraphicsGetImageFromCurrentImageContext();

        UIGraphicsEndImageContext();

        return img;
    }
Jared Chu
  • 2,757
  • 4
  • 27
  • 38