首页 > 解决方案 > 如何为 MPNowPlayingInfoCenter 设置艺术品图像

问题描述

我一直在尝试更新为MPNowPlayingInfoCenter使用中的项目显示的艺术品MPMediaItemPropertyArtwork,如以下代码所示,取自Apple 的文档

if let image = UIImage(named: "image_here") {
    nowPlayingInfo[MPMediaItemPropertyArtwork] =
        MPMediaItemArtwork(boundsSize: image.size) { size in
            return image
    }
}

我遇到的问题是,这会设置一个较小的图像,如下图红色方块所示。我试图弄清楚如何将图像设置在较大的黄色方块中,但我找不到任何可以区分两者的文档。

在此处输入图像描述

编辑

vint 在下面的回答澄清了较小的图标是应用程序图标。但是,我成功设置了 nowPlayingInfo 字典,因为我的其他元数据正在到达锁定屏幕控件,例如标题(模糊)、持续时间、已播放时间)。这只是看起来不起作用的艺术品。

标签: iosswiftxcodempmediaitem

解决方案


以防万一有人发现这个问题并且像我一样发疯,我可以通过正确调整我的大小来设置图像给回调函数UIImage的传入参数。正如文档中所说:sizeMPMediaItemArtwork

请求处理程序返回新请求大小的图像。请求的大小必须小于 boundsSize 参数。

然后用下面的扩展名将my设置image为传入参数,终于成功设置了。sizeMPMediaItemPropertyArtwork

extension UIImage {
    func imageWith(newSize: CGSize) -> UIImage {
        let renderer = UIGraphicsImageRenderer(size: newSize)
        let image = renderer.image { _ in
            self.draw(in: CGRect.init(origin: CGPoint.zero, size: newSize))
        }
        return image.withRenderingMode(self.renderingMode)
    }
}

if let image = UIImage(named: "image_here") {
    nowPlayingInfo[MPMediaItemPropertyArtwork] =
        MPMediaItemArtwork(boundsSize: image.size) { size in
            // Extension used here to return newly sized image
            return image.imageWith(newSize: size)
    }
}

推荐阅读