OSDN Git Service

swiftlint 'line_length'の警告を修正
[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 class ScreenshotCollectionViewItem: NSCollectionViewItem {
13     @IBOutlet weak var imageBox: NSBox!
14     @IBOutlet weak var nameField: NSTextField!
15     @IBOutlet weak var nameBox: NSBox!
16     
17     var info: ScreenshotInformation? {
18         return representedObject as? ScreenshotInformation
19     }
20     var imageFrame: NSRect {
21         guard let imageView = imageView
22             else { fatalError("ScreenshotCollectionViewItem: imageView is nil") }
23         let frame = centerFitRect(imageView.image, target: imageView.frame)
24         return view.convert(frame, from: imageBox)
25     }
26     
27     override var isSelected: Bool {
28         didSet {
29             (imageBox.fillColor, nameField.textColor, nameBox.fillColor) = {
30                 if isSelected {
31                     return (NSColor.controlHighlightColor, NSColor.white, NSColor.alternateSelectedControlColor)
32                 } else {
33                     return (NSColor.white, NSColor.black, NSColor.white)
34                 }
35             }()
36         }
37     }
38     
39     private func centerFitRect(_ image: NSImage?, target: NSRect) -> NSRect {
40         guard let image = image else { return target }
41         let imageSize = image.size
42         
43         var ratio: CGFloat = 1
44         let ratioX = target.size.height / imageSize.height
45         let ratioY = target.size.width / imageSize.width
46         if ratioX > ratioY {
47             ratio = ratioY
48         } else {
49             ratio = ratioX
50         }
51         let fitSize = NSSize(width: imageSize.width * ratio, height: imageSize.height * ratio)
52         let left = (target.size.width - fitSize.width) * 0.5
53         let bottom = (target.size.height - fitSize.height) * 0.5
54         return NSRect(x: left, y: bottom, width: fitSize.width, height: fitSize.height)
55     }
56 }
57
58 extension ScreenshotCollectionViewItem: QLPreviewItem {
59     var previewItemURL: URL! {
60         return info?.url
61     }
62 }