Change subview layer position - xcode

Good evening,
I have been trying to figure out how to fade a screen when I press a button in order to give a subview a more distinct appearance. I have researched zPositions and I thought that implementing this feature within my code would help. When I run my code, the entire screen fades. I would like there to be a circle progress ring that shows up, while the background is faded. I will show a picture and my code. Thank you in advance.
#objc func handlePost() {
let center = view.center
let trackLayer = CAShapeLayer()
let circularPath = UIBezierPath(arcCenter: center, radius: 100, startAngle: -CGFloat.pi / 2, endAngle: 2 * CGFloat.pi, clockwise: true)
blackScreen=UIView(frame: self.view.bounds)
blackScreen.backgroundColor=UIColor(white: 0, alpha: 0.8)
blackScreen.isHidden=true
self.navigationController?.view.addSubview(blackScreen)
blackScreen.layer.zPosition=50
blackScreen.isHidden=false
self.view.backgroundColor = UIColor.white
trackLayer.path = circularPath.cgPath
trackLayer.strokeColor = UIColor.lightGray.cgColor
trackLayer.lineWidth = 10
trackLayer.fillColor = UIColor.clear.cgColor
trackLayer.lineCap = kCALineCapRound
// The zPosition is supposed to bring this layer to the front.
trackLayer.zPosition = 100
shapeLayer.path = circularPath.cgPath
shapeLayer.strokeColor = GREEN_Theme.cgColor
shapeLayer.lineWidth = 10
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.lineCap = kCALineCapRound
shapeLayer.strokeEnd = 0
// The zPosition is supposed to bring this layer to the front.
shapeLayer.zPosition = 100
let basicAnimation = CABasicAnimation(keyPath: "strokeEnd")
basicAnimation.toValue = 1
basicAnimation.duration = 2
basicAnimation.fillMode = kCAFillModeForwards
basicAnimation.isRemovedOnCompletion = false
shapeLayer.add(basicAnimation, forKey: "dataSearch")
shapeLayer.removeAnimation(forKey: "finished")
view.layer.addSublayer(trackLayer)
view.layer.addSublayer(shapeLayer)
}

Again after spending hours with my code, I managed to figure out my own answer.
before I had
self.navigationController?.view.addSubview(blackScreen)
// (faded screen)
I simply needed to add
self.view.addSubview(blackScreen)
to turn it into a layer that way I could manipulate it with my zPosition.

Related

NSTextField text not showing

I am trying to draw a text with background color and border radius, but the text does not show.
I've used sizeToFit to make the textfield fit its content.
When the below code is added to its superview, this is what is shown:
As you can see, the text is missing even though the view has adjusted itself to fit the text. I have tried setting a huge frame but its the same issue.
let text = NSTextField(frame: NSRect(x: 0, y: 0, width: 0, height: 0))
text.stringValue = "ABC"
text.sizeToFit()
text.wantsLayer = true
text.isBordered = true
text.drawsBackground = true
let textFieldLayer = CALayer()
text.layer = textFieldLayer
text.backgroundColor = NSColor.blue
text.layer?.backgroundColor = NSColor.blue.cgColor
text.layer?.borderColor = NSColor.red.cgColor
text.layer?.borderWidth = 1
text.layer?.cornerRadius = 5
text.textColor = NSColor.red
let positionRelativeToScreen = toOrigin(point: positionFlipped, size: text.frame.size)
let positionRelativeToWindow = borderWindow.convertPoint(fromScreen: positionRelativeToScreen)
text.frame.origin = positionRelativeToWindow
return text
Solution was to remove textFieldLayer. Thanks #Willeke!

CGWindowListCreateImage yields blurred cgImage when zoomed

I'm developing a magnifying glass like application for mac. My goal is to be able to pinpoint individual pixels when zoomed in. I'm using this code in mouseMoved(with event: NSEvent):
let captureSize = self.frame.size.width / 9 //9 is the scale factor
let screenFrame = (NSScreen.main()?.frame)!
let x = floor(point.x) - floor(captureSize / 2)
let y = screenFrame.size.height - floor(point.y) - floor(captureSize / 2)
let windowID = CGWindowID(self.windowNumber)
cgImageExample = CGWindowListCreateImage(CGRect(x: x, y: y, width: captureSize,
height: captureSize), CGWindowListOption.optionOnScreenBelowWindow, windowID,
CGWindowImageOption.bestResolution)
The creation of the cgImage takes place in the CGWindowListCreateImage method. When I later draw this in an NSView, the result looks like this:
It looks blurred / like some anti-aliasing was applied during the creation of the cgImage. My goal is to get a razor sharp representation of each pixel. Can anyone point me in the right direction?
Ok, I figured it out. It was a matter of setting the interpolation quality to none on the drawing context:
context.interpolationQuality = .none
Result:
On request some more code:
//get the context
guard let context = NSGraphicsContext.current()?.cgContext else { return }
//get the CGImage
let image: CGImage = //pass the result from CGWindowListCreateImage call
//draw
context.draw(image, in: (CGRect of choice))

Animate CALayer - zoom and scroll

I want to create an animation with CALayers.
I have a parent layer with multiple sublayers and I would like to zoom in and scroll.
First I trying to zoom on the parent layer, as follows:
let transformAnimation = CABasicAnimation(keyPath: "bounds.size.width")
transformAnimation.duration = 2.3
transformAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
transformAnimation.toValue = 650*2
transformAnimation.beginTime = CACurrentMediaTime() + 4
transformAnimation.autoreverses = false
transformAnimation.isRemovedOnCompletion = false
transformAnimation.fillMode = kCAFillModeForwards
parentLayer.add(transformAnimation, forKey: "transformAnimation")
//
let transformAnimation2 = CABasicAnimation(keyPath: "bounds.size.height")
transformAnimation2.duration = 2.3
transformAnimation2.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
transformAnimation2.toValue = 650*2 //CGAffineTransform.identity
transformAnimation2.beginTime = CACurrentMediaTime() + 4
transformAnimation2.autoreverses = false
transformAnimation2.isRemovedOnCompletion = false
transformAnimation2.fillMode = kCAFillModeForwards
parentLayer.add(transformAnimation2, forKey: "transformAnimation2")
When the animation is applied, the sublayers are left in wrong position and size. Should I also apply the animation to them?
How can I do this?
Thanks!
I'm guessing that you're updating width and height of one layer and you're wondering whether the bounds of sublayers will also change. No, you'll probably have to animate those separately, too. But rather than initiating separate animations, you can them with a CAAnimationGroup.
If these were views, you could define constraints that coordinate the resizing of subviews more gracefully. But with layers, you're going to have to do this yourself. (There might be reasons why you're doing it the way you are, but it's not clear from the question.)

Physics body as an SKTexture does not rotate

I am making a game where the main character rotates, however, I want to use an SKTexture to set custom boundaries to the character sprite node. However, when I do this, my character does not rotate. When I use a regular circleOfRadius (because my sprite is round, but no perfectly round) it rotates, but is not accurate on collisions. Here is my code:
var mainSpriteTexture = SKTexture(imageNamed: "Main")
mainSprite = SKSpriteNode(texture: mainSpriteTexture)
mainSprite.setScale(0.2)
mainSprite.position = CGPoint(x: self.frame.width / 2, y: 100)
mainSprite.physicsBody = SKPhysicsBody(texture: mainSpriteTexture, size: mainSprite.size)
mainSprite.physicsBody?.categoryBitMask = PhysicsCatagory.player
mainSprite.physicsBody?.collisionBitMask = PhysicsCatagory.platform | PhysicsCatagory.ground
mainSprite.physicsBody?.contactTestBitMask = PhysicsCatagory.platform | PhysicsCatagory.ground | PhysicsCatagory.score
mainSprite.physicsBody?.affectedByGravity = true
mainSprite.physicsBody?.dynamic = true
mainSprite.physicsBody?.allowsRotation = true
self.addChild(mainSprite)
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
updateSpritePosition()
if gameStarted == true {
if died == false {
mainSprite.physicsBody?.velocity = CGVectorMake(direction, (mainSprite.physicsBody?.velocity.dy)!)
}
else if died == true {
mainSprite.physicsBody?.velocity = CGVectorMake(0, (mainSprite.physicsBody?.velocity.dy)!)
}
}
Here is the shape I am using: http://imgur.com/JCeEAbv
Not really sure how you rotate your sprite, or move it, but if I give it a certain default rotation and drop it on the surface, it rotates for me as it should (I used a picture you have provided). This way, it will not land perfectly on the ground (zRotation 0.0).
Try to use this:
mainSprite.zRotation = 0.1 //note that these are radians
and drop it on a flat surface.
Same thing you could probably achieve by applying a small force or impulse which should affect sprite's zRotation property... What you are going to use, depends on how you move your node actually - using physics, or by changing its position property directly (see my comment about mixing physics & manual node movement for important details).

Adding and removing NSTextField programatically in SWIFT OS X

I am trying to write text labels on a graph view representing a variety of data points (imagine a line graph in Excel).
I select a data set using a tableView. Each time a select a new data set the graph is redrawn.
I can draw the line graph using a custom view. No problems.
I can draw the text labels using the following function called from drawRect():
func drawDataPointLabels(size: CGSize) { //size is the view.bounds
var dataLabelsArray: [(NSColor, String, NSRect)] = []
// graphDetails contain an array of tuples [(), (), (), ()] - this represents one graph type = eg Monthly Fees ** there will be a maximum of 12 items in the array
for graphDetails in graphDetailsArray {
// each dataPoint object is a tuple (graphType: columnLabel: columnColor: columnHeight: columnNumber: ) representing one dataPoint
for dataPoint in graphDetails {
let graphHeight = size.height / 2
let graphWidth = size.width - graphOrigin.x - rightMargin
let columnAndGapSize = graphWidth / 25
let labelX: CGFloat = (graphOrigin.x + columnAndGapSize) + (columnAndGapSize * dataPoint.columnNumber) * 2
let labelY: CGFloat = dataPoint.columnHeight * (graphHeight - topMargin - bottomMargin)
// determine the location and frame for the text label to match dataPoint
let textFrame = NSRect(x: labelX, y: labelY, width: 30, height: 10)
let dataPointTuple = (dataPoint.columnColor, dataPoint.columnLabel, textFrame)
dataLabelsArray.append(dataPointTuple)
}
for dataPoint in dataLabelsArray {
let (color, label, frameRect) = dataPoint
let lblDataPoint = NSTextField(frame: frameRect)
lblDataPoint.stringValue = label
lblDataPoint.backgroundColor = backgroundColor
lblDataPoint.textColor = color
self.addSubview(lblDataPoint)
}
}
}
However, I can not work out how to remove the data labels when the view is updated and a new data set presented. The graph redraws but the text labels remain from the previous data set.
Any guidance/suggestions would be appreciated.
Adding the following code to the top of the function has solved the issue for me.
let subViewsToRemove = self.subviews
for object in subViewsToRemove {
object.removeFromSuperview()
}

Resources