OSDN Git Service

guard の書き方を統一した
[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 else { fatalError("ScreenshotCollectionViewItem: imageView is nil") }
26         
27         let frame = centerFitRect(imageView.image, target: imageView.frame)
28         
29         return view.convert(frame, from: imageBox)
30     }
31     
32     override var isSelected: Bool {
33         
34         didSet {
35             (imageBox.fillColor, nameField.textColor, nameBox.fillColor) = {
36                 
37                 if isSelected {
38                     
39                     return (NSColor.controlHighlightColor, NSColor.white, NSColor.alternateSelectedControlColor)
40                     
41                 } else {
42                     
43                     return (NSColor.white, NSColor.black, NSColor.white)
44                 }
45             }()
46         }
47     }
48     
49     private func centerFitRect(_ image: NSImage?, target: NSRect) -> NSRect {
50         
51         guard let image = image else { return target }
52         
53         let imageSize = image.size
54         
55         var ratio: CGFloat = 1
56         let ratioX = target.size.height / imageSize.height
57         let ratioY = target.size.width / imageSize.width
58         if ratioX > ratioY {
59             
60             ratio = ratioY
61             
62         } else {
63             
64             ratio = ratioX
65         }
66         let fitSize = NSSize(width: imageSize.width * ratio, height: imageSize.height * ratio)
67         let left = (target.size.width - fitSize.width) * 0.5
68         let bottom = (target.size.height - fitSize.height) * 0.5
69         
70         return NSRect(x: left, y: bottom, width: fitSize.width, height: fitSize.height)
71     }
72 }
73
74 extension ScreenshotCollectionViewItem: QLPreviewItem {
75     
76     var previewItemURL: URL! {
77         
78         return info?.url
79     }
80 }
81
82 extension ScreenshotCollectionViewItem: NibLoadable { }