首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在iOS中设置MediaItemArtwork图像填充UITableViewCell?

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

Stack Overflow用户
提问于 2013-01-31 22:26:40
回答 2查看 1.1K关注 0票数 2

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

代码语言:javascript
运行
复制
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's单元格ImageView中插入图片图像时没有问题。

但当我的作品图像太小或太大时,就会发生如图所示的情况。不能完全填写单元格的ImageView。

你看到了吗?我想像iOS音乐应用一样设置Fill with Stretch

这是内置的应用程序图片,完全用Stretch填充

我想这样做。

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

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-02-01 22:16:16

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

代码语言:javascript
运行
复制
// 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;
票数 4
EN

Stack Overflow用户

发布于 2013-02-01 21:19:33

这条线

代码语言:javascript
运行
复制
UIImage *artworkImage = [artwork imageWithSize: cell.imageView.bounds.size];

创建具有单元格大小的图像。所以,它是在这条线上缩放的,图像不会比单元格大,因此它不会在之后缩放。

我会让图像保持原始大小,或者是单元格大小的2倍,并将缩放比例保留为contentMode

代码语言:javascript
运行
复制
CGSize newSize = CGSizeMake(artwork.bounds.size.width, artwork.bounds.size.height)
UIImage *artworkImage = [artwork imageWithSize: newSize];
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14628101

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档