MacOS-02-窗体自定义视图并保存为图片

//
// AppDelegate.swift
// View
//
// Created by iDevFans on 16/6/25.
// Copyright © 2016年 http://www.macdev.io. All rights reserved.
//
AppDelegate.swift

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

@IBOutlet weak var window: NSWindow!
@IBOutlet weak var customView: CustomView!

func applicationDidFinishLaunching(_ aNotification: Notification) {
    // 动态生成按钮
    let button = NSButton()
    let frame = NSRect(x: 2, y: 2, width: 80, height: 18)
    button.frame = frame
    button.title = "Register"
    button.bezelStyle = .rounded //按钮样式        
    self.customView.addSubview(button) //加载到视图
    self.customView.postsFrameChangedNotifications = true //是否发送大小改变通知
    
   
}
///Marker:注册一个通知小心
func registerNotification() {
     NotificationCenter.default.addObserver(self, selector:#selector(self.recieveFrameChangeNotification(_:)),  name:NSView.frameDidChangeNotification, object: nil)
}


@objc func recieveFrameChangeNotification(_ notification: Notification){
    
}
///Marker: 保存为图片
@IBAction func captureAction(_ sender: NSButton) {
    self.customView.saveSelfAsImage()
}

}

CustomView.swift

//
// CustomView.swift
// View
//
// Created by iDevFans on 16/6/25.
// Copyright © 2016年 http://www.macdev.io. All rights reserved.
//

import Foundation
import AppKit
// MARK: 创建自定义视图
final class CustomView: NSView {

//类初始化
override init(frame frameRect: NSRect) {
    super.init(frame: frameRect)
}
 
required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.configLayer()  //配置层方法
}
//坐标的已左上角为(0,0)
override var isFlipped: Bool {
    get {
        return true
    }
}

// MARK: Event 鼠标按下时间
override func mouseDown(with theEvent: NSEvent) {
    let point = self.convert(theEvent.locationInWindow, to: nil) //将本地坐标转换成视图坐标 
    NSLog("window point: \(theEvent.locationInWindow)")
    NSLog("view point: \(point)")
}
//Mark: 层设置
func configLayer(){
    self.wantsLayer = true  //是否启用层
    self.layer?.backgroundColor = NSColor.red.cgColor //设置层的颜色
    self.layer?.borderWidth = 2  //设置边框宽度
    self.layer?.cornerRadius = 10  //设置层的圆角
}

// MARK :  Draw 重载绘制方法
override func draw(_ dirtyRect: NSRect) {
    super.draw(dirtyRect)
    NSColor.blue.setFill()  //设置填充色
    let frame = self.bounds  //获取当前层的bounds
    let path = NSBezierPath()  //定义一个贝尔路径
    path .appendRoundedRect(frame, xRadius: 20, yRadius: 20) // 
    path.fill() //开始填充
}
//绘制文字图形
func drawViewShape(){
    self.lockFocus()  //锁定视图 -在swift5.0中被废弃
    //NSRectFill(self.bounds)
    let text: NSString = "RoundedRect"  
    let font = NSFont(name: "Palatino-Roman", size: 12)
    let attrs = [NSAttributedStringKey.font :font! ,
                    NSAttributedStringKey.foregroundColor :NSColor.blue,NSAttributedStringKey.backgroundColor :NSColor.red]
    let loaction = NSPoint(x: 50, y: 50)
    text.draw(at: loaction, withAttributes: attrs) //开始绘制文本
    self.unlockFocus() //解锁
}
/// Marker: 保存视图为图片
func saveScrollViewAsImage() {
    let pdfData = self.dataWithPDF(inside: self.bounds) //获取视图的大小数据
    let imageRep = NSPDFImageRep(data: pdfData)!  //可以将pdf转化为一个图片 https://developer.apple.com/documentation/appkit/nspdfimagerep
    let count = imageRep.pageCount
    for i in 0..<count {
        imageRep.currentPage = i  //获取指定页的数据
        let tempImage = NSImage()
        tempImage.addRepresentation(imageRep)  //转图像 1
        let rep  = NSBitmapImageRep(data:tempImage.tiffRepresentation!) //转bitmap图像 2
        let imageData = rep?.representation(using:.png, properties: [:])  //设置要保存的图片格式
        let fileManager = FileManager.default  // https://developer.apple.com/documentation/foundation/filemanager/1409234-default
        //写死的文件路径
        let path = "/Users/idevfans/Documents/myCapture.png"
        fileManager.createFile(atPath: path, contents: imageData, attributes: nil)//创建文件
        
        //定位文件路径
        let fileURL = URL(fileURLWithPath: path)
        NSWorkspace.shared.activateFileViewerSelecting([fileURL]) //弹出文件保存页面窗口
    }
}
/// Marker: 保存为图片
func saveSelfAsImage() {
    self.lockFocus()   //锁定视图 -在swift5.0中被废弃
    let image = NSImage(data:self.dataWithPDF(inside: self.bounds)) //获取
    self.unlockFocus()  //解锁
    let imageData = image!.tiffRepresentation  //返回bitmap data
    
    let fileManager = FileManager.default
    //写死的文件路径
    let path = "/Users/idevfans/Documents/myCapture.png"
    fileManager.createFile(atPath: path, contents: imageData, attributes: nil)
    
    //定位文件路径
    let fileURL = URL(fileURLWithPath: path)
    NSWorkspace.shared.activateFileViewerSelecting([fileURL])
}

}

猜你喜欢

转载自blog.csdn.net/txfsnow_1979/article/details/93479990
今日推荐