调整图像大小但保留硬边

问题描述 投票:1回答:3

我正在使用这个链接中的一段代码 - Resize UIImage by keeping Aspect ratio and width,它工作得很好,但我想知道它是否可以改变以保留像素的硬边缘。我希望将图像的大小加倍并保持像素的硬边缘。

class func resizeImage(image: UIImage, newHeight: CGFloat) -> UIImage {

    let scale = newHeight / image.size.height
    let newWidth = image.size.width * scale
    UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight))
    image.drawInRect(CGRectMake(0, 0, newWidth, newHeight))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage
}

What I want it to do

What it does

在Photoshop中,调整大小时会有最近邻插值,在iOS中有类似的东西吗?

ios xcode swift image image-resizing
3个回答
2
投票

受到接受的答案的启发,更新到Swift 5。

斯威夫特5

let image = UIImage(named: "Foo")!
let scale: CGFloat = 2.0

let newSize = image.size.applying(CGAffineTransform(scaleX: scale, y: scale))
UIGraphicsBeginImageContextWithOptions(newSize, false, UIScreen.main.scale)
let context = UIGraphicsGetCurrentContext()!
context.interpolationQuality = .none
let newRect = CGRect(origin: .zero, size: newSize)
image.draw(in: newRect)

let newImage = UIImage(cgImage: context.makeImage()!)
UIGraphicsEndImageContext()

1
投票

多挖一点,找到了答案 -

https://stackoverflow.com/a/25430447/4196903

但是哪里

CGContextSetInterpolationQuality(context, kCGInterpolationHigh)

而是写

CGContextSetInterpolationQuality(context, CGInterpolationQuality.None)

0
投票

您需要使用CISamplerclass(仅在iOS 9中可用)并且需要为它创建自己的自定义图像处理过滤器

你可以找到更多信息herehere too

© www.soinside.com 2019 - 2024. All rights reserved.