1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swift:NSImageのドット絵をそのまま拡大(リサイズ)する

Last updated at Posted at 2019-01-20

概要

画像のリサイズのときImageViewの機能の余計なお世話で勝手に色を補間してしまいますよね.(特にScalingProportionally Up or Downなんか選ぶと)ドット絵を用いる時はこの仕様は邪魔ですね.そこで,画像のリサイズの際,補間をさせずにそのまま拡大する方法を調べて実装してみました.

ソース

resizeというExtensionを書いてみました.

extension NSImage {
    public func resize(targetSize: CGSize) -> NSImage? {
        let wRatio = targetSize.width / self.size.width
        let hRatio = targetSize.height / self.size.height
        var newSize: CGSize
        if(wRatio > hRatio) {
            newSize = CGSize(width: self.size.width * hRatio,
                             height: self.size.height * hRatio)
        } else {
            newSize = CGSize(width: self.size.width * wRatio,
                             height: self.size.height * wRatio)
        }
        guard let imageData = self.tiffRepresentation else { return nil }
        guard let cgImage = NSBitmapImageRep(data: imageData)?.cgImage else { return nil }
        guard let bitmapContext = CGContext(data: nil,
                                            width: Int(newSize.width),
                                            height: Int(newSize.height),
                                            bitsPerComponent: 8,
                                            bytesPerRow: 4 * Int(newSize.width),
                                            space: CGColorSpaceCreateDeviceRGB())//   DeviceGray(),
                                            bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil }
        
        let rect = CGRect(origin: CGPoint.zero, size: newSize)
        bitmapContext.interpolationQuality = CGInterpolationQuality.none
        bitmapContext.draw(cgImage, in: rect)
        guard let newImageRef = bitmapContext.makeImage() else { return nil }
        let newImage = NSImage(cgImage: newImageRef, size: newSize)
        return newImage
    }
}
使用例
let imageView = NSImageView(frame: NSRect(x: 0, y: 0, width: 200, height: 100))
let nsImage = NSImage(imageLiteralResourceName: "DotImage")
imageView.image = nsImage.resize(targetSize: imageView.frame.size)
1
3
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?