调整图像大小但保留硬边
Resizing an image but preserving hard edges
我正在使用 link - 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中有类似的东西吗?
进一步挖掘并找到了答案 -
但是
CGContextSetInterpolationQuality(context, kCGInterpolationHigh)
改为写
CGContextSetInterpolationQuality(context, CGInterpolationQuality.None)
您需要使用 CISampler
class(仅在 iOS 9 中可用)并且我认为需要为其创建您自己的自定义图像处理过滤器
受已接受答案的启发,更新为Swift 5.
Swift 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()
我正在使用 link - 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中有类似的东西吗?
进一步挖掘并找到了答案 -
但是
CGContextSetInterpolationQuality(context, kCGInterpolationHigh)
改为写
CGContextSetInterpolationQuality(context, CGInterpolationQuality.None)
您需要使用 CISampler
class(仅在 iOS 9 中可用)并且我认为需要为其创建您自己的自定义图像处理过滤器
受已接受答案的启发,更新为Swift 5.
Swift 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()