CATiledLayer in NSView flashes on changing contentsScale - swift

I have a CATiledLayer inside a NSView which is a documentView property of NSScrollView.
Storyboard setup is pretty straitforward: add NSScrollView to the default view controller and assign View class to the NSView of clipping view.
The following code draws a number of squares of random color. Scrolling works exactly as it should in CATiledLayer but zooming doesn't work very well:
Found tons of CATiledLayer problems and all the proposed solutions don't work for me (like subclassing with 0 fadeDuration or disabling CATransaction actions). I guess that setNeedsDisplay() screws it all but can't figure out the proper way to do that. If I use CALayer then I don't see the flashing issues but then I can't deal with large layers of thousands of boxes inside.
The View class source:
import Cocoa
import CoreGraphics
import Combine
let rows = 1000
let columns = 1000
let width = 50.0
let height = 50.0
class View: NSView {
typealias Coordinate = (x: Int, y: Int)
private let colors: [[CGColor]]
private let rect = CGRect(origin: .zero, size: CGSize(width: width, height: height))
private var store = Set<AnyCancellable>()
private var scale: CGFloat {
guard let scrollView = self.superview?.superview as? NSScrollView else { fatalError() }
return NSScreen.main!.backingScaleFactor * scrollView.magnification
}
required init?(coder: NSCoder) {
colors = (0..<rows).map { _ in (0..<columns).map { _ in .random } }
super.init(coder: coder)
setFrameSize(NSSize(width: width * CGFloat(columns), height: height * CGFloat(rows)))
wantsLayer = true
NotificationCenter.default.publisher(for: NSScrollView.didEndLiveMagnifyNotification).sink { [unowned self] _ in
self.layer?.contentsScale = scale
self.layer?.setNeedsDisplay()
}.store(in: &store)
}
override func makeBackingLayer() -> CALayer {
let layer = CATiledLayer()
layer.tileSize = CGSize(width: 1000, height: 1000)
return layer
}
override func draw(_ dirtyRect: NSRect) {
guard let context = NSGraphicsContext.current?.cgContext else { return }
let (min, max) = coordinates(in: dirtyRect)
context.translateBy(x: CGFloat(min.x) * width, y: CGFloat(min.y) * height)
(min.y...max.y).forEach { row in
context.saveGState()
(min.x...max.x).forEach { column in
context.setFillColor(colors[row][column])
context.addRect(rect)
context.drawPath(using: .fillStroke)
context.translateBy(x: width, y: 0)
}
context.restoreGState()
context.translateBy(x: 0, y: height)
}
}
private func coordinates(in rect: NSRect) -> (Coordinate, Coordinate) {
var minX = Int(rect.minX / width)
var minY = Int(rect.minY / height)
var maxX = Int(rect.maxX / width)
var maxY = Int(rect.maxY / height)
if minX >= columns {
minX = columns - 1
}
if maxX >= columns {
maxX = columns - 1
}
if minY >= rows {
minY = rows - 1
}
if maxY >= rows {
maxY = rows - 1
}
return ((minX, minY), (maxX, maxY))
}
}
extension CGColor {
class var random: CGColor {
let random = { CGFloat(arc4random_uniform(255)) / 255.0 }
return CGColor(red: random(), green: random(), blue: random(), alpha: random())
}
}

To be able to support zooming into a CATiledLayer, you set the layer's levelOfDetailBias. You don't need to observe the scroll view's magnification notifications, change the layers contentScale, or trigger manual redraws.
Here's a quick implementation that shows what kinds of dirtyRects you get at different zoom levels:
class View: NSView {
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
wantsLayer = true
}
required init?(coder: NSCoder) {
super.init(coder: coder)
wantsLayer = true
}
override func makeBackingLayer() -> CALayer {
let layer = CATiledLayer()
layer.tileSize = CGSize(width: 400, height: 400)
layer.levelsOfDetailBias = 3
return layer
}
override func draw(_ dirtyRect: NSRect) {
let context = NSGraphicsContext.current!
let scale = context.cgContext.ctm.a
NSColor.red.setFill()
dirtyRect.frame(withWidth: 10 / scale, using: .overlay)
NSColor.black.setFill()
let string: NSString = "Scale: \(scale)" as NSString
let attributes = [NSAttributedString.Key.font: NSFont.systemFont(ofSize: 40 / scale)]
let size = string.size(withAttributes: attributes)
string.draw(at: CGPoint(x: dirtyRect.midX - size.width / 2, y: dirtyRect.midY - size.height / 2),
withAttributes: attributes)
}
}
The current drawing contexts is already scaled to match the current zoom level (and the dirtyRect's get smaller and smaller for each level of detail down). You can extract the current scale from CGContext's transformation matrix as shown above, if needed.

Related

The background mask cuts off part of the foreground layer

Recently ran into a problem in one of my tasks. I tried to solve this problem for two days. Finally I came here.
I have a custom progress view. Don't look at the colors, they are so awful just for the debugging process to see better.
[the look I have now] 1
[the look I want to have] 2
As you can see, there is a red dot at the end of the progress layer, but it is cut at the top and bottom ...
And it shouldn't be like that ...
Also I will leave here all the code I have, maybe someone
can help me.
Thank you all in advance for your time.
import UIKit
class PlainProgressBar: UIView {
//MARK: - Private
//colour of progress layer : default -> white
private var color: UIColor = .white {
didSet { setNeedsDisplay() }
}
// progress numerical value
private var progress: CGFloat = 0.0 {
didSet { setNeedsDisplay() }
}
private var height : CGFloat = 0.0 {
didSet{ setNeedsDisplay() }
}
private let progressLayer = CALayer()
private let dotLayer = CALayer()
private let backgroundMask = CAShapeLayer()
private func setupLayers() {
layer.addSublayer(progressLayer)
layer.addSublayer(dotLayer)
}
//MARK:- Public
// set color for progress layer
func setColor(progressLayer color: UIColor){
self.color = color
}
func set(progress: CGFloat){
if progress > 1.0{
self.progress = 1.0
}
if progress < 0.0{
self.progress = 0.0
}
if progress >= 0.0 && progress <= 1.0{
self.progress = progress
}
}
func set(height: CGFloat){
self.height = height
}
override init(frame: CGRect) {
super.init(frame: frame)
setupLayers()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupLayers()
}
//Main draw function for view
override func draw(_ rect: CGRect) {
backgroundMask.path = UIBezierPath(roundedRect: CGRect(origin: .zero, size: CGSize(width: rect.width, height: height)), cornerRadius: rect.height * 0.25).cgPath
layer.mask = backgroundMask
let dotOnProgressLayer = CGRect(origin: .zero, size: CGSize(width: 10.0, height: 10.0))
let progressRect = CGRect(origin: .zero, size: CGSize(width: rect.width * progress, height: height))
progressLayer.frame = progressRect
progressLayer.backgroundColor = color.cgColor
dotLayer.frame = dotOnProgressLayer
dotLayer.cornerRadius = dotLayer.bounds.width * 0.5
dotLayer.backgroundColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1).cgColor
dotLayer.position = CGPoint(x: progressLayer.frame.width ,y: progressLayer.frame.height / 2)
}
}
progressView.set(height: 4.5)
progressView.setColor(progressLayer: UIColor(ciColor: .green))
You are masking the views layer with
layer.mask = backgroundMask
So anything outside the mask will no be drawn.

Cropping is not working perfectly as per the frame drawn

I am trying to crop a selected portion of NSImage which is fitted as per ProportionallyUpOrDown(AspectFill) Mode.
I am drawing a frame using mouse dragged event like this:
class CropImageView: NSImageView {
var startPoint: NSPoint!
var shapeLayer: CAShapeLayer!
var flagCheck = false
var finalPoint: NSPoint!
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
}
override var image: NSImage? {
set {
self.layer = CALayer()
self.layer?.contentsGravity = kCAGravityResizeAspectFill
self.layer?.contents = newValue
self.wantsLayer = true
super.image = newValue
}
get {
return super.image
}
}
override func mouseDown(with event: NSEvent) {
self.startPoint = self.convert(event.locationInWindow, from: nil)
if self.shapeLayer != nil {
self.shapeLayer.removeFromSuperlayer()
self.shapeLayer = nil
}
self.flagCheck = true
var pixelColor: NSColor = NSReadPixel(startPoint) ?? NSColor()
shapeLayer = CAShapeLayer()
shapeLayer.lineWidth = 1.0
shapeLayer.fillColor = NSColor.clear.cgColor
if pixelColor == NSColor.black {
pixelColor = NSColor.color_white
} else {
pixelColor = NSColor.black
}
shapeLayer.strokeColor = pixelColor.cgColor
shapeLayer.lineDashPattern = [1]
self.layer?.addSublayer(shapeLayer)
var dashAnimation = CABasicAnimation()
dashAnimation = CABasicAnimation(keyPath: "lineDashPhase")
dashAnimation.duration = 0.75
dashAnimation.fromValue = 0.0
dashAnimation.toValue = 15.0
dashAnimation.repeatCount = 0.0
shapeLayer.add(dashAnimation, forKey: "linePhase")
}
override func mouseDragged(with event: NSEvent) {
let point: NSPoint = self.convert(event.locationInWindow, from: nil)
var newPoint: CGPoint = self.startPoint
let xDiff = point.x - self.startPoint.x
let yDiff = point.y - self.startPoint.y
let dist = min(abs(xDiff), abs(yDiff))
newPoint.x += xDiff > 0 ? dist : -dist
newPoint.y += yDiff > 0 ? dist : -dist
let path = CGMutablePath()
path.move(to: self.startPoint)
path.addLine(to: NSPoint(x: self.startPoint.x, y: newPoint.y))
path.addLine(to: newPoint)
path.addLine(to: NSPoint(x: newPoint.x, y: self.startPoint.y))
path.closeSubpath()
self.shapeLayer.path = path
}
override func mouseUp(with event: NSEvent) {
self.finalPoint = self.convert(event.locationInWindow, from: nil)
}
}
and selected this area as shown in picture using black dotted line:
My Cropping Code logic is this:
// resize Image Methods
extension CropProfileView {
func resizeImage(image: NSImage) -> Data {
var scalingFactor: CGFloat = 0.0
if image.size.width >= image.size.height {
scalingFactor = image.size.width/cropImgView.size.width
} else {
scalingFactor = image.size.height/cropImgView.size.height
}
let width = (self.cropImgView.finalPoint.x - self.cropImgView.startPoint.x) * scalingFactor
let height = (self.cropImgView.startPoint.y - self.cropImgView.finalPoint.y) * scalingFactor
let xPos = ((image.size.width/2) - (cropImgView.bounds.midX - self.cropImgView.startPoint.x) * scalingFactor)
let yPos = ((image.size.height/2) - (cropImgView.bounds.midY - (cropImgView.size.height - self.cropImgView.startPoint.y)) * scalingFactor)
var croppedRect: NSRect = NSRect(x: xPos, y: yPos, width: width, height: height)
let imageRef = image.cgImage(forProposedRect: &croppedRect, context: nil, hints: nil)
guard let croppedImage = imageRef?.cropping(to: croppedRect) else {return Data()}
let imageWithNewSize = NSImage(cgImage: croppedImage, size: NSSize(width: width, height: height))
guard let data = imageWithNewSize.tiffRepresentation,
let rep = NSBitmapImageRep(data: data),
let imgData = rep.representation(using: .png, properties: [.compressionFactor: NSNumber(floatLiteral: 0.25)]) else {
return imageWithNewSize.tiffRepresentation ?? Data()
}
return imgData
}
}
With this cropping logic i am getting this output:
I think as image is AspectFill thats why its not getting cropped in perfect size as per selected frame. Here if you look at output: xpositon & width & heights are not perfect. Or probably i am not calculating these co-ordinates properly. Let me know the faults probably i am calculating someting wrong.
Note: the CropImageView class in the question is a subclass of NSImageView but the view is layer-hosting and the image is drawn by the layer, not by NSImageView. imageScaling is not used.
When deciding which scaling factor to use you have to take the size of the image view into account. If the image size is width:120, height:100 and the image view size is width:120, height 80 then image.size.width >= image.size.height is true and image.size.width/cropImgView.size.width is 1 but the image is scaled because image.size.height/cropImgView.size.height is 1.25. Calculate the horizontal and vertical scaling factors and use the largest.
See How to crop a UIImageView to a new UIImage in 'aspect fill' mode?
Here's the calculation of croppedRect assuming cropImgView.size returns self.layer!.bounds.size.
var scalingWidthFactor: CGFloat = image.size.width/cropImgView.size.width
var scalingHeightFactor: CGFloat = image.size.height/cropImgView.size.height
var xOffset: CGFloat = 0
var yOffset: CGFloat = 0
switch cropImgView.layer?.contentsGravity {
case CALayerContentsGravity.resize: break
case CALayerContentsGravity.resizeAspect:
if scalingWidthFactor > scalingHeightFactor {
scalingHeightFactor = scalingWidthFactor
yOffset = (cropImgView.size.height - (image.size.height / scalingHeightFactor)) / 2
}
else {
scalingWidthFactor = scalingHeightFactor
xOffset = (cropImgView.size.width - (image.size.width / scalingWidthFactor)) / 2
}
case CALayerContentsGravity.resizeAspectFill:
if scalingWidthFactor < scalingHeightFactor {
scalingHeightFactor = scalingWidthFactor
yOffset = (cropImgView.size.height - (image.size.height / scalingHeightFactor)) / 2
}
else {
scalingWidthFactor = scalingHeightFactor
xOffset = (cropImgView.size.width - (image.size.width / scalingWidthFactor)) / 2
}
default:
print("contentsGravity \(String(describing: cropImgView.layer?.contentsGravity)) is not supported")
return nil
}
let width = (self.cropImgView.finalPoint.x - self.cropImgView.startPoint.x) * scalingWidthFactor
let height = (self.cropImgView.startPoint.y - self.cropImgView.finalPoint.y) * scalingHeightFactor
let xPos = (self.cropImgView.startPoint.x - xOffset) * scalingWidthFactor
let yPos = (cropImgView.size.height - self.cropImgView.startPoint.y - yOffset) * scalingHeightFactor
var croppedRect: NSRect = NSRect(x: xPos, y: yPos, width: width, height: height)
Bugfix: cropImgView.finalPoint should be the corner of the selection, not the location of mouseUp. In CropImageView set self.finalPoint = newPoint in mouseDragged instead of mouseUp.

Why are these CAShapeLayers not going where expected?

I'm working on a custom loading indicator and am having a lot of issues with CAShapeLayers.
The loading indicator will be contained within a custom UIView so that any viewController can use it.
First issue:
The frame of the subview is not matching the bounds.
When using this code to display a circle in each corner of the frame the circles are placed in a square shape but it is no where near the view.
import UIKit
View Controller:
class MergingCicles: UIViewController, HolderViewDelegate {
func animateLabel() {
}
var holderView = HolderView(frame: CGRect.zero)
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
addHolderView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func addHolderView() {
let boxSize: CGFloat = 100.0
holderView.frame = CGRect(x: view.bounds.width / 2 - boxSize / 2,
y: view.bounds.height / 2 - boxSize / 2,
width: boxSize,
height: boxSize)
holderView.parentFrame = view.frame
holderView.delegate = self
holderView.center = self.view.center
view.addSubview(holderView)
holderView.addCircleLayer()
}
}
Subview:
Import UIKit
protocol HolderViewDelegate:class {
func animateLabel()
}
class HolderView: UIView {
let initalLayer = InitialLayer()
let triangleLayer = TriangleLayer()
let redRectangleLayer = RectangleLayer()
let blueRectangleLayer = RectangleLayer()
let arcLayer = ArcLayer()
var parentFrame :CGRect = CGRect.zero
weak var delegate:HolderViewDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.clear
}
required init(coder: NSCoder) {
super.init(coder: coder)!
}
func addCircleLayer() {
var circleLocations = [CGPoint]()
let offset = CircleLayer().maxSize / 2
circleLocations.append(CGPoint(x: self.frame.maxX - offset, y: self.frame.maxY - offset))
circleLocations.append(CGPoint(x: self.frame.minX + offset, y: self.frame.minY + offset))
circleLocations.append(CGPoint(x: self.frame.maxX - offset, y: self.frame.minY + offset))
circleLocations.append(CGPoint(x: self.frame.minX + offset, y: self.frame.maxY - offset))
circleLocations.append(layer.anchorPoint)
for point in circleLocations {
let circle = CircleLayer()
circle.updateLocation(Size: .medium, center: point)
self.layer.addSublayer(circle)
}
self.backgroundColor = .blue
// layer.anchorPoint = CGPoint(x: (self.bounds.maxX + self.bounds.maxX)/2, y: (self.bounds.maxY + self.bounds.minY)/2)
let rotationAnimation: CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotationAnimation.toValue = CGFloat(Double.pi * 2)
rotationAnimation.duration = 0.45
rotationAnimation.isCumulative = true
//rotationAnimation.repeatCount = 1000
//rotationAnimation.isRemovedOnCompletion = true
// layer.add(rotationAnimation, forKey: nil)
}
}
Circle Layer:
import Foundation
import UIKit
enum ShapeSize {
case medium
case small
case large
}
class CircleLayer: CAShapeLayer {
let animationDuration: CFTimeInterval = 0.3
let maxSize = CGFloat(50)
override init() {
super.init()
fillColor = UIColor.red.cgColor
}
func updateLocation(Size: ShapeSize, center: CGPoint){
switch Size {
case .medium:
path = UIBezierPath(ovalIn: CGRect(x: center.x, y: center.y, width: maxSize/3, height: maxSize/3)).cgPath
case .small:
path = UIBezierPath(ovalIn: CGRect(x: center.x, y: center.y, width: (2*maxSize)/3, height: (2*maxSize)/3)).cgPath
case .large:
path = UIBezierPath(ovalIn: CGRect(x: center.x, y: center.y, width: maxSize, height: maxSize)).cgPath
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Result:
This really shows that the frame is no where near the uiView.
If I change addCircleLayer to use bounds instead I get something much closer:
But still the circles are not in the corners (except the bottom right one, that one is correct). It appears there is some extra space on the left and top of the view that is not captured using self.bounds.
The ultimate goal is to also rotate the circles 360 degrees around the center but as shown by the circle in the upper left corner the layer anchor is not in the center of the view, I changed the anchor to be the center of the circles but then nothing appeared on screen at all.
You're saying things like
circleLocations.append(CGPoint(x: self.frame.maxX - offset, y: self.frame.maxY - offset))
But self.frame is where the view is located in its own superview. Thus, the shape layer ends up offset from the view by as much as the view is offset from its own superview. Wherever you say frame here, you mean bounds.
I found the problem was then when drawing the circles I was using UIBezierPath(ovalIn:CGRect, width: CGFloat, height: CGFloat which was using the x value for the left side of the circle. When I changed to UIBezierPath(arcCenter: CGPoint, radius: CGFloat, startAngle: CGFloat, endAngle: CGFloat, clockwise: Bool) the point was used for the center of the circle and made it all fit where expected when using self.bounds to calculate the points.
After that I no longer had to change the anchor point as it was in the correct location by default.
I didn't figure out why the frame is in a completely different spot but it is no longer impacting the project.

Drawing an NSBezierPath Shape with NSView Subclass

I'm trying to draw a shape that is created with NSBezierPath on an NSView canvas. I've created a subclass of NSView.
// NSView //
import Cocoa
class DisplayView: NSView {
var path: NSBezierPath
var fillColor: NSColor
var strokeColor: NSColor
var weight: CGFloat
init(frame: CGRect, path: NSBezierPath, fillColor: NSColor, strokeColor: NSColor, weight: CGFloat){
self.path = path
self.fillColor = fillColor
self.strokeColor = strokeColor
self.weight = weight
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ dirtyRect: NSRect) {
path.lineWidth = weight
fillColor.set()
path.fill()
strokeColor.set()
path.stroke()
}
}
// NSViewController //
import Cocoa
class ViewController: NSViewController {
// MARK: - IBOutlet
#IBOutlet weak var canvasView: NSView!
override func viewDidLoad() {
super.viewDidLoad()
override func viewDidLoad() {
super.viewDidLoad()
let path = Shapes.circle(maxSize: 100) // a path from a separate class
let rect = CGRect(x: 20, y: 20, width: 200, height: 200)
let pathView = DisplayView(frame: rect, path: path, fillColor: NSColor.green, strokeColor: NSColor.white, weight: 6.0)
canvasView.addSubview(pathView)
}
}
And I get the following result. How come the edges are broken by half the line weight on two sides? The path object is only a size of 100 pts x 100 pts. Thanks.
UPDATE
The following is the code for making a path object.
class Shapes {
static func circle(maxSize: CGFloat) -> NSBezierPath {
let oval = NSBezierPath.init(ovalIn: CGRect(x: 0.0 * maxSize, y: 0.0 * maxSize, width: 1.0 * maxSize, height: 1.0 * maxSize))
oval.close()
return oval
}
}
You have created your bezier path with an origin of 0,0. As a result, the thicker border gets clipped by the view it is rendered in (your DisplayView class).
You need to create your path so the origin is (weight / 2 + 1) instead of 0.
Or you can apply a translate transform to the graphics context and shift the origin by (weight / 2 + 1.
override func draw(_ dirtyRect: NSRect) {
let ctx = NSGraphicsContext.current!.cgContext
ctx.saveGState()
let offset = weight / 2 + 1
ctx.translateBy(x: offset, y: offset)
path.lineWidth = weight
fillColor.set()
path.fill()
strokeColor.set()
path.stroke()
ctx.restoreGState()
}

NSImageView mouseDragged Value pass back to windowController

Can anyone please show me how to get the position X and Y back to my WindowController NSTextField (testTextX and testTextY)?
I created a windowController, NSImage and NSTextField programmatically. I added an image "dot" to the NSView and would like the "dot" image draggable and return the position X and Y.
I manage to have the image added and draggable but I do not know how can I pass the position X and Y on mouseDragged back to the NSTextField at my WindowController (testTextX and testTextY)?
The current display as below, when click on the "dot" image, it is draggrable to any position.
I can print out the position X and Y from the NSImageView func mouseDragged(theEvent: NSEvent) when image was dragged.
I am stuck at the how to pass the position X and Y back to WindowController.
My WindowController.swift code as below:
public class MyWindowController: NSWindowController, NSWindowDelegate {
// MARK: Constants
// 1. Define min&max window size
var fWidth:CGFloat = 0
var fHeight:CGFloat = 0
var vWidth:CGFloat = 0
var vHeight:CGFloat = 0
var blankPage: NSView!
var viewDotImg: NSImageView!
var testTextX: NSTextField!
var testTextY: NSTextField!
var modalWinHeight: CGFloat = 0
var m_window:NSWindow = NSWindow()
// MARK: Initializer
init(){
super.init(window: self.m_window)
}
init(channelId:Int){
super.init(window:self.m_window)
// Get the window full width and height
fWidth = (NSScreen.mainScreen()?.frame.width)!
fHeight = (NSScreen.mainScreen()?.frame.height)!
// Get the window visible width and height
vWidth = (NSScreen.mainScreen()?.visibleFrame.width)!
vHeight = (NSScreen.mainScreen()?.visibleFrame.height)!
// Get the position X and Y for Window
let winPosX: CGFloat = fWidth - vWidth
let winPosY: CGFloat = fHeight - vHeight
// Divide the height by 3
let avgHeight: CGFloat = vHeight / 3
// Set the max window height as avgHeight * 1.3
let modalWinHeight: CGFloat = avgHeight * 1.3
// Set the window frame
self.m_window = NSWindow(contentRect: NSMakeRect(winPosX, winPosY, vWidth, modalWinHeight),
styleMask: NSClosableWindowMask | NSMiniaturizableWindowMask | NSTitledWindowMask,
backing: NSBackingStoreType.Buffered, `defer`: false);
// Window delegate
self.m_window.delegate = self
// Add a blank NSView with Gradian background colour
blankPage = CGradiantBlank(x: x, y:y, width:width, height: height)
self.window?.contentView = blankPage
// Add Image Dot to NSView
viewDotImg = DragNSImageView(x: 200, y: 200, width: 10, height: 10)
// Add Two TextField to NSView
testTextX = TextLabel(x: 200, y: 10, width: 100, height: 24, value: "100")
testTextY = TextLabel(x: 305, y: 10, width: 100, height: 24, value: "100")
blankPage.addSubview(viewDotImg)
blankPage.addSubview(testTextX)
blankPage.addSubview(testTextY)
}
func updTestXY(x:Double, y:Double){
testTextX.stringValue = String(x)
testTextY.stringValue = String(y)
}
override public init(window: NSWindow?) {
super.init(window: window)
}
required public init?(coder:NSCoder){
super.init(coder: coder)
}
}
My NSImageView code as below:
public class DragNSImageView: NSImageView {
private var xWidth: CGFloat = 0
private var xHeight: CGFloat = 0
init(x:CGFloat, y:CGFloat, width:CGFloat, height:CGFloat, chId: Int) {
super.init(frame: NSRect(x: x,y: y,width: width,height: height))
super.imageScaling = NSImageScaling.ScaleAxesIndependently
super.image = NSImage(named: "dot-10")
xWidth = width
xHeight = height
}
required public init?(coder: NSCoder) {
super.init(coder: coder)
}
override public func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
}
public override func mouseDragged(theEvent: NSEvent) {
super.mouseDown(theEvent)
let location = theEvent.locationInWindow
let pX: CGFloat = location.x
let pY: CGFloat = location.y
super.frame = NSRect(x: pX,y: pY,width: xWidth,height: xHeight)
Swift.print("X: \(location.x)" Y: \(location.y))
/* How to pass this location.x and location.y back to WindowController func updateTestXY()?
updTestXY(Double(location.x), y:Double(location.y))
*/
}
}
My NSTextField code as below:
public class TextLabel: NSTextField {
// MARK: Initializer
init(){
super.init(frame: NSRect(x: 0, y: 0, width: 90, height: 10))
}
convenience init(x:CGFloat, y:CGFloat, width:CGFloat, height:CGFloat, value:String){
self.init()
super.wantsLayer = true
super.backgroundColor = NSColor.darkGrayColor()
super.textColor = NSColor.whiteColor()
super.stringValue = value
super.frame = NSRect(x: x, y: y, width: width, height: height)
}
required public init?(coder: NSCoder) {
super.init(coder: coder)
}
override public func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
}
}
Ok, I found the solution.
let mainWindow = self.window?.windowController as! MyWindowController
mainWindow.updXY(location.x, y:location.y, refName: refName)
If more than one "dot" image, then add the following code to the NSImageView init()
super.identifier = "ReferenceName1"
Now, go to NSImageView mouseDragged(theEvent: NSEvent) method and add the following line:
let refName = super.identifier
This will be use at the MyWindowController to detect which "dot" image was dragged when calling the specified function. In my case, I call the
updXY(location.x, y:location.y, refName: refName)
So, at MyWindowController, I use the following to do the work.
public func updXy(x: CGFloat, y: CGFloat, refName: String){
if refName == "ReferenceName1" {
}else if refName == "ReferenceName2" {
}
}