OSDN Git Service

コード整形
[kcd/KCD.git] / KCD / ScreenshotCollectionViewItem.swift
1 //
2 //  ScreenshotCollectionViewItem.swift
3 //  KCD
4 //
5 //  Created by Hori,Masaki on 2016/12/29.
6 //  Copyright © 2016年 Hori,Masaki. All rights reserved.
7 //
8
9 import Cocoa
10 import Quartz
11
12 final class ScreenshotCollectionViewItem: NSCollectionViewItem {
13     
14     @IBOutlet weak var imageBox: NSBox!
15     @IBOutlet weak var nameField: NSTextField!
16     @IBOutlet weak var nameBox: NSBox!
17     
18     var info: ScreenshotInformation? {
19         
20         return representedObject as? ScreenshotInformation
21     }
22     
23     var imageFrame: NSRect {
24         
25         guard let imageView = imageView
26             else { fatalError("ScreenshotCollectionViewItem: imageView is nil") }
27         
28         let frame = centerFitRect(imageView.image, target: imageView.frame)
29         
30         return view.convert(frame, from: imageBox)
31     }
32     
33     override var isSelected: Bool {
34         
35         didSet {
36             (imageBox.fillColor, nameField.textColor, nameBox.fillColor) = {
37                 
38                 if isSelected {
39                     
40                     return (NSColor.controlHighlightColor, NSColor.white, NSColor.alternateSelectedControlColor)
41                     
42                 } else {
43                     
44                     return (NSColor.white, NSColor.black, NSColor.white)
45                 }
46             }()
47         }
48     }
49     
50     private func centerFitRect(_ image: NSImage?, target: NSRect) -> NSRect {
51         
52         guard let image = image else { return target }
53         
54         let imageSize = image.size
55         
56         var ratio: CGFloat = 1
57         let ratioX = target.size.height / imageSize.height
58         let ratioY = target.size.width / imageSize.width
59         if ratioX > ratioY {
60             
61             ratio = ratioY
62             
63         } else {
64             
65             ratio = ratioX
66         }
67         let fitSize = NSSize(width: imageSize.width * ratio, height: imageSize.height * ratio)
68         let left = (target.size.width - fitSize.width) * 0.5
69         let bottom = (target.size.height - fitSize.height) * 0.5
70         
71         return NSRect(x: left, y: bottom, width: fitSize.width, height: fitSize.height)
72     }
73 }
74
75 extension ScreenshotCollectionViewItem: QLPreviewItem {
76     
77     var previewItemURL: URL! {
78         
79         return info?.url
80     }
81 }