【发布时间】:2017-10-11 01:13:48
【问题描述】:
我正在尝试使用以下流行代码调整图像大小,它正在调整图像大小,但它正在将图像大小调整为 Scale to Fill,我想将它们调整为 Aspect Fit. 我该怎么做?
func resizeImage(image: UIImage, newSize: CGSize) -> (UIImage) {
let newRect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height).integral
UIGraphicsBeginImageContextWithOptions(newSize, true, 0)
let context = UIGraphicsGetCurrentContext()
// Set the quality level to use when rescaling
context!.interpolationQuality = CGInterpolationQuality.default
let flipVertical = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: newSize.height )
context!.concatenate(flipVertical)
// Draw into the context; this scales the image
context?.draw(image.cgImage!, in: CGRect(x: 0.0,y: 0.0, width: newRect.width, height: newRect.height))
let newImageRef = context!.makeImage()! as CGImage
let newImage = UIImage(cgImage: newImageRef)
// Get the resized image from the context and a UIImage
UIGraphicsEndImageContext()
return newImage
}
我已经将图片的内容模式设置为Aspect Fit,但还是不行。
这就是我在集合视图控制器中调用上述代码的方式
cell.imageView.image = UIImage(named: dogImages[indexPath.row])?.resizeImage(image: UIImage(named: dogImages[indexPath.row])
我在情节提要中手动选择了我的图像并将其内容模式设置为apsect fit
【问题讨论】:
-
这是我用来调整图像大小的一个很好的扩展gist.github.com/tomasbasham/10533743#gistcomment-1988471
-
我试过了,他们确实把它缩小到适合纵横比,但图像模糊
-
你能分享一下如何在视图中设置图像的代码吗?另外,您如何为上述视图设置 contentMode?span>
-
请查看已编辑的问题
-
我用过这个,效果很好stackoverflow.com/a/2025413/1926015
标签: ios swift core-graphics