OSDN Git Service

スクリーンショットをキャッシュするようにした
[kcd/KCD.git] / KCD / NSTextFieldExtension.swift
1 //
2 //  NSTextFieldExtension.swift
3 //  KCD
4 //
5 //  Created by Hori,Masaki on 2017/09/16.
6 //  Copyright © 2017年 Hori,Masaki. All rights reserved.
7 //
8
9 import Cocoa
10
11 extension NSTextField {
12     
13     func maskImage(middle1: CGFloat, middle2: CGFloat) -> CGImage {
14         
15         let colorspace = CGColorSpaceCreateDeviceGray()
16         
17         guard let maskContext = CGContext(data: nil,
18                                           width: Int(bounds.width),
19                                           height: Int(bounds.height),
20                                           bitsPerComponent: 8,
21                                           bytesPerRow: Int(bounds.width),
22                                           space: colorspace,
23                                           bitmapInfo: 0) else {
24                                             
25                                             fatalError("Can not create bitmap context")
26         }
27         
28         let maskGraphicsContext = NSGraphicsContext(cgContext: maskContext, flipped: false)
29         
30         NSGraphicsContext.saveGraphicsState()
31         defer { NSGraphicsContext.restoreGraphicsState() }
32         
33         NSGraphicsContext.current = maskGraphicsContext
34         
35         let gradient = NSGradient(colorsAndLocations: (.white, 0.0),
36                                   (.white, middle1),
37                                   (.black, middle2),
38                                   (.black, 1.0))
39         gradient?.draw(in: bounds, angle: 0.0)
40         
41         guard let r = maskContext.makeImage() else { fatalError(" can not create image from context") }
42         
43         return r
44     }
45     
46     func isCharacterProtrude() -> Bool {
47         
48         guard let currentFont = font else { return Logger.shared.log("TextField dose not set font", value: false) }
49         
50         let string = stringValue as NSString
51         let size = string.size(withAttributes: [.font: currentFont])
52         
53         return bounds.size.width - size.width < 3
54     }
55     
56 }