ios - 如何在iOS中设置MediaItemArtwork图像填充在UITableViewCell中?

标签 ios cocoa-touch uitableview mpmediaitem artwork

我正在尝试使用以下代码将 MPMediaItemArtwork 图像输入 UITableView's 单元格的 ImageView 中。

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

当我在UITableView的单元格ImageView中插入Artwork图像时,没问题。

但是当我的艺术作品图像太小或太大时,就会发生如下图所示的情况。 未完全填充单元格的 ImageView。

enter image description here

你看到了吗?我想像 iOS 音乐应用一样使用 Stretch 设置填充

这是内置应用程序图稿图像,设置完全填充拉伸(stretch)

enter image description here

我想这样做。

所以我使用了 cell.imageView.contentMode = UIViewContentModeScaleAspectFill; 但它没有效果。

那么我该怎么做呢? 感谢您的工作。

最佳答案

尝试使用此方法计算新的拟合图像; 将 newRect 调整为单元格的矩形。

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

关于ios - 如何在iOS中设置MediaItemArtwork图像填充在UITableViewCell中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14628101/

相关文章:

ios - 在 RegEx 标识的 NSString 中的某个点添加一个字符,是否有比所有反向引用更有效的方法?

ios - 为什么在呈现新的 UITableviewController 子类时,以前工作的 Xcode 项目会在 Xcode 7 中挂起?

iphone - 将单元格添加到 UITableView 顶部

iphone - 添加到 ALAssetGroup 时 ALAsset 的自定义文件名

android - delphi xe6 目标多字节代码页中不存在 Unicode 字符的映射

iphone - 我的应用程序的可读性

ios - 'required' initializer 'init(coder:)' 必须由 UIViewController 的子类提供

Objective-C:使用 NSString 变量将消息发送到各种对象之一

iOS - 在多个 View 中重复使用完全相同的单元格设计和代码

ios - 就地 UITableView 编辑 : Adding a row crash