ios - 缩放图像以适合 - iOS

标签 ios image swift uiimageview uicollectionviewcell

我有一个显示 12 个图像的 UICollectionView。图像不适合单元格,它们正在被裁剪,但我希望它们适合单元格而不被裁剪。

应该使图像比例适合的代码是:

 cell.imageView.contentMode = UIViewContentMode.ScaleAspectFit
 cell.imageView.image = UIImage(named: name)

这是我的整个 viewController 类的代码和屏幕截图:

import UIKit

class DressingRoomViewController:
        UIViewController,
        UICollectionViewDelegateFlowLayout,
        UICollectionViewDataSource {

    @IBOutlet weak var collectionView: UICollectionView!

    let identifier = "cellIdentifier"
    let dataSource = DataSource()

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView.dataSource = self
    }

    override func viewDidAppear(animated: Bool) {
        //  Notes on the equation to get the cell size:
        //  cells per row = 6
        //  cell spacing = 10
        //  collectionView.layout.inset = 20 (10 left, 10 right)
        let cellSize = (collectionView.collectionViewLayout
            .collectionViewContentSize().width - 20) / 6 - 10

        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()

        layout.sectionInset = UIEdgeInsets( top: 20,
                                            left: 10,
                                            bottom: 10,
                                            right: 10)

        layout.itemSize = CGSize(width: cellSize, height: cellSize)

        collectionView.collectionViewLayout = layout
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func prepareForSegue(  segue: UIStoryboardSegue,
                                    sender: AnyObject?) {
        if (segue.identifier == "dressingRoom2MyOutfits") {
            let myOutfitsViewController = segue.destinationViewController
                as! MyOutfitsViewController
        }
    }
}



// MARK:- UICollectionViewDataSource Delegate
extension DressingRoomViewController : UICollectionViewDataSource {

    func numberOfSectionsInCollectionView(
        collectionView: UICollectionView) -> Int {
            return 1
    }

    func collectionView(collectionView: UICollectionView,
        numberOfItemsInSection section: Int) -> Int {
            return 12
    }

    func collectionView(collectionView: UICollectionView,
        cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(
            identifier,forIndexPath:indexPath) as! FruitCell

        let fruits: [Fruit] = dataSource.fruits
        let fruit = fruits[indexPath.row]

        let name = fruit.name!

        cell.imageView.contentMode = UIViewContentMode.ScaleAspectFit
        cell.imageView.image = UIImage(named: name)

        return cell
    }
}

编辑:这是 FruitCell 类,以防万一你想知道。

    class FruitCell: UICollectionViewCell {

    @IBOutlet weak var imageView: UIImageView!

}

enter image description here

最佳答案

已从界面构建器放置在 UICollectionViewCell 中的 UIImageView 将不知道已以编程方式初始化的 UICollectionViewFlowLayout。因此,我设置的 layout.sectionInset 使 UICollectionViewCells 变小了,即使在界面生成器中创建的 UIImageView 被限制在 UICollectionViewCell 的边缘,UIImageView 也没有调整大小以变小。

解决方案是以编程方式初始化 UIImageView,并将大小设置为单元格的大小,同时考虑单元格间距。

代码如下:

import UIKit

class DressingRoomViewController:
        UIViewController,
        UICollectionViewDelegateFlowLayout,
        UICollectionViewDataSource {

    @IBOutlet weak var collectionView: UICollectionView!

    let identifier = "cellIdentifier"
    let dataSource = DataSource()
    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    let cellSpacing: CGFloat = 2
    let cellsPerRow: CGFloat = 6


    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView.dataSource = self
    }

    override func viewDidAppear(animated: Bool) {
        let cellSize = (collectionView.collectionViewLayout
            .collectionViewContentSize().width / cellsPerRow) - (cellSpacing)

        layout.itemSize = CGSize(width: cellSize, height: cellSize)
        layout.minimumInteritemSpacing = cellSpacing
        layout.minimumLineSpacing = cellSpacing
        collectionView.collectionViewLayout = layout
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func prepareForSegue(  segue: UIStoryboardSegue,
                                    sender: AnyObject?) {
        if (segue.identifier == "dressingRoom2MyOutfits") {
            let myOutfitsViewController = segue.destinationViewController
                as! MyOutfitsViewController
        }
    }
}



// MARK:- UICollectionViewDataSource Delegate
extension DressingRoomViewController : UICollectionViewDataSource {

    func numberOfSectionsInCollectionView(
        collectionView: UICollectionView) -> Int {
            return 1
    }

    func collectionView(collectionView: UICollectionView,
        numberOfItemsInSection section: Int) -> Int {
            return 12
    }

    func collectionView(collectionView: UICollectionView,
        cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(
            identifier,forIndexPath:indexPath) as! FruitCell

        let fruits: [Fruit] = dataSource.fruits
        let fruit = fruits[indexPath.row]

        let name = fruit.name!

        var imageView :UIImageView
        imageView = UIImageView(frame:CGRectMake(   0,
                                                    0,
            (collectionView.collectionViewLayout
                .collectionViewContentSize().width / cellsPerRow)
                - (cellSpacing),
            (collectionView.collectionViewLayout
                .collectionViewContentSize().width / cellsPerRow)
                - (cellSpacing)))

        imageView.contentMode = UIViewContentMode.ScaleAspectFit
        imageView.image = UIImage(named: name)
        imageView.backgroundColor = UIColor.redColor()
        cell.addSubview(imageView)

        return cell
    }
}

编辑:我能够通过为高度约束创建一个导出(控制 + 将界面构建器中的高度约束拖动到 viewController swift 文件)调用它 heightConstraint 来裁剪掉 UICollectionView 底部的空白区域,并且然后在viewDidAppear底部添加这两行代码:

self.heightConstraint.constant = collectionView.contentSize.height
self.view.layoutIfNeeded()

为了向您展示 UICollectionView 的白色背景和 UIImageViews 的红色背景的结果,结果如下(也适用于所有其他设备尺寸):

enter image description here

关于ios - 缩放图像以适合 - iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32198069/

相关文章:

ios - Restkit:执行我自己的 RKMapperOperation 时创建重复对象

ios - 人们如何使用 React Native 处理 iOS 中的 "recent app"箭头?

javascript - 如何制作 Javascript/jQuery/HTML 动画图像堆栈

swift - 如何在允许 JWT 刷新的同时检查 Swift 中的 Auth 用户?

ios - 相邻的 UILabel 不会换行

ios - 如何检测音量加减被按下

ios - 如何使用照片框架快速循环浏览照片库

javascript - 通过 <img>-tag 注入(inject) javascript

python - OpenCV 中的图像扭曲

ios - 如何在swift3中检查当前字符串是24小时格式时间还是12小时格式时间?