【问题标题】:Resizing an image but preserving hard edges调整图像大小但保留硬边
【发布时间】:2016-05-16 06:23:32
【问题描述】:

我正在使用此链接中的一段代码 - 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


    【解决方案1】:

    受到公认答案的启发,已更新至 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()
    

    【讨论】:

      【解决方案2】:

      做了更多的挖掘并找到了答案 -

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

      但是在哪里

      CGContextSetInterpolationQuality(context, kCGInterpolationHigh)
      

      改为写

      CGContextSetInterpolationQuality(context, CGInterpolationQuality.None)
      

      【讨论】:

        【解决方案3】:

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

        您可以找到更多信息herehere too

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-08-20
          • 2019-11-29
          • 1970-01-01
          • 2013-09-09
          • 2012-07-08
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多