Jared Chu Jared Chu - 1 month ago 12
iOS Question

Rectangle image scale to aspect fit square to use with MPMediaItemArtwork

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

problem is resolved



I 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;
}

Answer

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;
    }