矩形图像缩放到纵横比适合与MPMediaItemArtwork一起使用

时间:2016-11-02 08:57:40

标签: ios objective-c uiimage

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

我的UIImagerectangle,当我使用MPNowPlayingInfoCenter将其放到MPMediaItemArtwork时,它会被裁剪成正方形。如何调整UIImage的大小以适应宽度square UIImage并将其余部分留空?

enter image description here

1 个答案:

答案 0 :(得分:2)

UIImage放入UIImageViewcontentMode设为UIImageViewUIViewContentModeScaleAspectFit并将其呈现回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;
    }