如何使用 swift 在 ios 中获取方形裁剪照片缩略图

How to get square cropped photo thumbnail in ios using swift

我想为我的 collection 视图单元格获取照片缩略图,我是这样做的:

imageManager.requestImageForAsset(asset as! PHAsset, targetSize:CGSizeMake(80, 80), contentMode: .AspectFit, options: nil, resultHandler: {(result, info)->Void in
        cell.setThumbnail(result!)
    }   
})

这将得到一个被拉伸的缩略图,我想要一个方形的裁剪缩略图,以保持照片的原始比例,就像 iPhone 的照片应用所做的那样。

有什么想法吗?请在 swift 中回复,因为我是 ios 编程新手,我从 swift 开始,谢谢。

如果您使用的是 Interface Builder,您可以在其中设置 UIImageView 的属性,请查看以下两个属性:

视图模式会影响它看起来是否拉伸或是否适合。但是,有时,即使它在技术上适合,但如果您的图像太大,它仍可能溢出单元格矩形的边界。在这种情况下,您可以启用 "Clip Subviews",这将确保图像不会显示在图像视图矩形的边界之外。

如果您不使用 Interface Builder,则可以改为在代码中的单元格上设置这两个属性,即:

// This is assuming your UIImageView inside your cell is
// called 'thumbnail'. You could put this code inside of your
// .setThumbnail() function instead--though it's not clear
// what all that is doing from you code snippet.
cell.thumbnail.clipsToBounds = true
cell.thumbnail.contentMode = .ScaleAspectFill

您可以选择的各种内容模式在 UIKit 中是这样定义的:

public enum UIViewContentMode : Int {

    case ScaleToFill
    case ScaleAspectFit // contents scaled to fit with fixed aspect. remainder is transparent
    case ScaleAspectFill // contents scaled to fill with fixed aspect. some portion of content may be clipped.
    case Redraw // redraw on bounds change (calls -setNeedsDisplay)
    case Center // contents remain same size. positioned adjusted.
    case Top
    case Bottom
    case Left
    case Right
    case TopLeft
    case TopRight
    case BottomLeft
    case BottomRight
}