I want my swift code to draw a line like the place of a x axis. So the line is in the center of the screen no matter what screen size the object is displayed in. My code below produces a line but it does not account for the device size. My image below displays a black line which is what my current code produces and the orange line is the desired output.
Pic
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let lineView = UIView(frame: CGRect(x: 0, y: 100, width: 320, height: 1.0))
lineView.layer.borderWidth = 1.0
lineView.layer.borderColor = UIColor.black.cgColor
self.view.addSubview(lineView)
}
}
To draw a line in the middle of the screen, just assign the Line.swift file to UIView on which you want to draw a line.
Line.swift file
class Line:UIView {
var line = UIBezierPath()
func drawLine() {
line.move(to: CGPoint(x: 0, y: bounds.height / 2))
line.addLine(to: CGPoint(x: (bounds.width) , y: bounds.height / 2))
UIColor.black.setStroke()
line.lineWidth = 0.1
line.stroke()
}
override func draw(_ rect: CGRect) {
drawLine()
}
}
To assign it to your UIView, open the main.storyboard and click on the view where you want to draw the line. Then, go into upper right tabs which would look like this
You can see inside the class field, there is a placeholder called "UIView". Type there Line and hit enter, and then just run the project. You 'll be able to see the line in the middle of the view. No need to declare or call any function. Just assign this class and run the project.
If you want to respond with the width of the view, you can use constraints:
override func viewDidLoad() {
super.viewDidLoad()
let lineView = UIView()
lineView.translatesAutoresizingMaskIntoConstraints = false
lineView.layer.borderWidth = 1
lineView.layer.borderColor = UIColor.black.cgColor
view.addSubview(lineView)
NSLayoutConstraint.activate([
lineView.leftAnchor.constraint(equalTo: view.leftAnchor),
lineView.rightAnchor.constraint(equalTo: view.rightAnchor),
lineView.topAnchor.constraint(equalTo: view.topAnchor, constant: 100),
lineView.heightAnchor.constraint(equalToConstant: 1)
])
}
For what it’s worth, rather than drawing lines using the border of a view, I'd define a UIBezierPath and use that for a CAShapeLayer’s path:
#IBDesignable
class GraphView: UIView {
let shapeLayer: CAShapeLayer = {
let shapeLayer = CAShapeLayer()
shapeLayer.lineWidth = 2
shapeLayer.strokeColor = UIColor.black.cgColor
shapeLayer.fillColor = UIColor.clear.cgColor
return shapeLayer
}()
override init(frame: CGRect = .zero) {
super.init(frame: frame)
layer.addSublayer(shapeLayer)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
layer.addSublayer(shapeLayer)
}
override func layoutSubviews() {
super.layoutSubviews()
let path = UIBezierPath()
path.move(to: CGPoint(x: bounds.minX, y: 100))
path.addLine(to: CGPoint(x: bounds.maxX, y: 100))
shapeLayer.path = path.cgPath
}
}
Then you can add this view to your view hierarchy like shown above, or right in Interface Builder (obviously, defining the constraints in IB, too).
Related
I use SnapKit in my project and trying to add gradient on my button
I have extension:
extension UIButton {
public func setGradientColor(colorOne: UIColor, colorTwo: UIColor) {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = bounds
gradientLayer.colors = [colorOne.cgColor, colorTwo.cgColor]
gradientLayer.locations = [0.0, 1.0]
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.0)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0)
layer.insertSublayer(gradientLayer, at: 0)
}
}
i have button config where i am trying to use gradient:
private var playersButton: UIButton = {
let button = UIButton(type: .custom)
button.setGradientColor(colorOne: .red, colorTwo: .blue)
button.frame = button.layer.frame
return button
}()
and SnapKit here
playersButton.snp.makeConstraints { make in
make.leading.equalToSuperview().inset(60)
make.trailing.equalToSuperview().inset(60)
make.bottom.equalTo(startGameButton).inset(100)
make.height.equalTo(screenHeight/12.82)
}
The problem is i have not result of it, i dont see gradientm but if i delete snapKit config and will use setGradient extension in viewDidLoad it works well!
Example:
private var playersButton: UIButton = {
let button = UIButton(type: .custom)
button.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
playersButton.setGradientColor(colorOne: .blue, colorTwo: .red)
}
How do i change my code to use first method? Thank you
The difference is that when using SnapKit you're using Auto-Layout, so your button's frame is not set when you call button.setGradientColor(colorOne: .red, colorTwo: .blue).
The result is that your gradient layer ends up with a frame size of Zero - so you don't see it.
You will likely find it much easier and more reliable to use a button subclass like this (simple example based on the code you posted):
class MyGradientButton: UIButton {
let gradLayer = CAGradientLayer()
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() {
layer.insertSublayer(gradLayer, at: 0)
}
public func setGradientColor(colorOne: UIColor, colorTwo: UIColor) {
gradLayer.colors = [colorOne.cgColor, colorTwo.cgColor]
gradLayer.locations = [0.0, 1.0]
gradLayer.startPoint = CGPoint(x: 0.0, y: 0.0)
gradLayer.endPoint = CGPoint(x: 1.0, y: 1.0)
}
override func layoutSubviews() {
super.layoutSubviews()
gradLayer.frame = bounds
}
}
Then change your button declaration to:
private var playersButton: MyGradientButton = {
let button = MyGradientButton()
button.setGradientColor(colorOne: .red, colorTwo: .blue)
return button
}()
Now, whether you set its frame explicitly, or if you use auto-layout (normal syntax or with SnapKit), the gradient layer will automatically adjust whenever the button's frame changes.
I am trying to create an overlay view, that has a "cutout" part that comes from a frame that is passed to the view, that size and position of that passed frame will change upon creation of the view. And in that "cutout" part I am expecting to see the content that is under that overlay view. Tried to set border to a rounded rectangle that is added to a CGMutablePath, but no luck.
The expected result is something like this:
The code I currently have in my UIView class, without tried solutions as I can't seem to get them to work properly. This current code displays the expected result, but without the red border:
override func draw(_ rect: CGRect) {
super.draw(rect)
UIColor.blue.setFill()
UIRectFill(rect)
let shapeLayer = CAShapeLayer()
let path = CGMutablePath()
// frame that will change position on the screen
if let frame = changingFrame {
path.addRoundedRect(in: frame, cornerWidth: 16, cornerHeight: 16)
}
path.addRect(bounds)
shapeLayer.path = path
shapeLayer.fillRule = CAShapeLayerFillRule.evenOdd
self.layer.mask = shapeLayer
}
I have tried solutions from here, here, but no luck as CAShapeLayer for border just overlays existing one.
What can I do differently to achieve the expected result? Thanks!
try this ⭐️
If all you want to do is create a rounded rectangle, then you can simply use.
let rectangle = CGRect(x: 0, y: 0, width: 100, height: 100)
let path = UIBezierPath(roundedRect: rectangle, cornerRadius: 20)
view.clipsToBounds = true
view.layer.cornerRadius = 10.0
let border = CAShapeLayer()
border.path = UIBezierPath(roundedRect:view.bounds, cornerRadius:10.0).cgPath
border.frame = view.bounds
border.fillColor = nil
border.strokeColor = UIColor.purple.cgColor
border.lineWidth = borderWidth * 2.0 // doubled since half will be clipped
border.lineDashPattern = [1.0]
view.layer.addSublayer(border)
One approach is to use two sublayers... a "cutout" layer and a "border" layer.
Use the same path for the cutout and the border shape, setting the line width and stroke color for the "outline".
Here's an example -- including making it #IBDesignable with a few #IBInspectable properties:
#IBDesignable
class BorderedCutoutView: UIView {
#IBInspectable
var bkgColor: UIColor = .systemBlue {
didSet {
setNeedsLayout()
}
}
#IBInspectable
var brdColor: UIColor = .white {
didSet {
setNeedsLayout()
}
}
#IBInspectable
var brdWidth: CGFloat = 1 {
didSet {
setNeedsLayout()
}
}
#IBInspectable
var radius: CGFloat = 20 {
didSet {
setNeedsLayout()
}
}
#IBInspectable
var horizInset: CGFloat = 40.0 {
didSet {
setNeedsLayout()
}
}
#IBInspectable
var vertInset: CGFloat = 60.0 {
didSet {
setNeedsLayout()
}
}
private let cutoutLayer = CAShapeLayer()
private let borderLayer = CAShapeLayer()
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
backgroundColor = .clear
}
private func commonInit() -> Void {
backgroundColor = .clear
layer.addSublayer(cutoutLayer)
layer.addSublayer(borderLayer)
}
override func layoutSubviews() {
super.layoutSubviews()
let path = UIBezierPath(rect: bounds)
let cp = UIBezierPath(roundedRect: bounds.insetBy(dx: horizInset, dy: vertInset), cornerRadius: radius)
path.append(cp)
path.usesEvenOddFillRule = true
cutoutLayer.path = path.cgPath
cutoutLayer.fillRule = .evenOdd
cutoutLayer.fillColor = bkgColor.cgColor
borderLayer.path = cp.cgPath
borderLayer.fillColor = UIColor.clear.cgColor
borderLayer.lineWidth = brdWidth
borderLayer.strokeColor = brdColor.cgColor
}
}
This example uses horizontal and vertical "inset" values to center the cutout in the view.
Result:
Hi I am trying to set CAShapeLayer inside to NSView. But I can't set corner radius of the CAShapeLayer outside of draw(_ dirtyRect: NSRect) function.
I have to use CAShapeLayer to set NSBezierPath to draw custom shapes. So, that only I am using CAShapeLayer instead of the NSView's default CALayer.
Here is the code:
extension NSBezierPath
extension NSBezierPath {
var cgPath: CGPath {
let path = CGMutablePath()
var points = [CGPoint](repeating: .zero, count: 3)
for i in 0 ..< elementCount {
let type = element(at: i, associatedPoints: &points)
switch type {
case .moveTo: path.move(to: points[0])
case .lineTo: path.addLine(to: points[0])
case .curveTo: path.addCurve(to: points[2], control1: points[0], control2: points[1])
case .closePath: path.closeSubpath()
#unknown default:
fatalError("Unknown!")
}
}
return path
}
}
CustomView.swift
class CustomView: NSView{
let shapeLayer = CAShapeLayer()
var cornerRadius: CGFloat {
set{
let path = NSBezierPath(roundedRect: bounds, xRadius: newValue, yRadius: newValue)
shapeLayer.path = path.cgPath
path.close()
}
get{
return shapeLayer.cornerRadius
}
}
var backgroundColor: NSColor{
set{
shapeLayer.fillColor = newValue.cgColor
}
get{
return NSColor(cgColor: shapeLayer.backgroundColor ?? .clear)!
}
}
init() {
super.init(frame: .zero)
wantsLayer = true
shapeLayer.masksToBounds = true
layer?.addSublayer(shapeLayer)
// layer?.mask = shapeLayer
// layer?.masksToBounds = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ dirtyRect: NSRect) {
shapeLayer.frame = dirtyRect
let path = NSBezierPath(rect: dirtyRect)
shapeLayer.path = path.cgPath
// shapeLayer.cornerRadius = 22
shapeLayer.borderColor = NSColor.black.cgColor
shapeLayer.borderWidth = 2.0
path.close()
}
}
ViewController.swift
class ViewController: NSViewController {
private lazy var customView: CustomView = {
let customView = CustomView()
view.addSubview(customView)
customView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
customView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
customView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
customView.heightAnchor.constraint(equalToConstant: 44),
customView.widthAnchor.constraint(equalToConstant: 144)
])
return customView
}()
override func viewDidLoad() {
super.viewDidLoad()
// customView.layer?.cornerRadius = 22
customView.backgroundColor = .red
customView.cornerRadius = 22
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
Current output:
Expected Output:
Code is commented in the attached codes..
Please help me to solve this problem. Thank you in advance...
The following is a simple example. First, draw a simple rectangle with a subclass of NSView. So instantiate it to make an object with a view controller. Then use object's layer to make it a round rect with a stroke color.
// Subclass of `NSView` //
import Cocoa
class MyView: NSView {
var fillColor: NSColor
init(frame: CGRect, fillColor: NSColor){
self.fillColor = fillColor
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: NSRect) {
super.draw(rect)
let path = NSBezierPath()
path.move(to: CGPoint.zero)
path.line(to: CGPoint(x: 0.0, y: self.frame.height))
path.line(to: CGPoint(x: self.frame.width, y: self.frame.height))
path.line(to: CGPoint(x: self.frame.width, y: 0.0))
path.line(to: CGPoint.zero)
fillColor.set()
path.fill()
}
}
// View controller //
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
let rect = CGRect(origin: CGPoint(x: 50, y: 50), size: CGSize(width: 200, height: 50))
let myView = MyView(frame: rect, fillColor: NSColor.red)
myView.wantsLayer = true
if let myLayer = myView.layer {
myLayer.cornerRadius = 24.0
myLayer.borderWidth = 4.0
//myLayer.borderColor = NSColor.green.cgColor
}
view.addSubview(myView)
}
}
so I am implementing a simple gradient on the lower half a UIView subclass like the following
however, every time I leave the app and reenter it, the gradient gets darker, and so forth. How do I make it so it just stays the same shade?
Here is my code for the gradient. I don't know if its correct to place it in layoutSubviews, but I couldn't get it to work just by calling the gradient code directly, such as in viewDidLoad for example:
override func layoutSubviews() {
let gradientLayer = CAGradientLayer()
gradientLayer.type = .axial
gradientLayer.colors = [UIColor.clear.cgColor, UIColor.black.cgColor]
gradientLayer.frame = bounds
gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
gradientLayer.endPoint = .init(x: 0, y: 1)
gradientLayer.zPosition = 1
gradientLayer.opacity = 0.5
layer.addSublayer(gradientLayer)
}
layoutSubviews() gets called multiple times, so your gradient is getting added repeatedly.
layoutSubviews() is not really the place to be adding this gradient. The reason adding it in viewDidLoad() was not working for you is because the bounds of the view haven't been established yet. Go ahead and set up your gradient in viewDidLoad(). Keep the gradient as a property, and use viewDidLayoutSubviews() to update the frame.
class ViewController: UIViewController {
let gradientLayer = CAGradientLayer()
override func viewDidLoad() {
super.viewDidLoad()
gradientLayer.type = .axial
gradientLayer.colors = [UIColor.clear.cgColor, UIColor.black.cgColor]
gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
gradientLayer.endPoint = .init(x: 0, y: 1)
gradientLayer.zPosition = 1
gradientLayer.opacity = 0.5
view.layer.addSublayer(gradientLayer)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
gradientLayer.frame = view.bounds
}
}
For a view that is a subclass of UIView, you'd handle it like this:
class MyView: UIView {
let gradientLayer = CAGradientLayer()
override init(frame: CGRect) {
super.init(frame: frame)
addGradient()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
addGradient()
}
func addGradient() {
gradientLayer.type = .axial
gradientLayer.colors = [UIColor.clear.cgColor, UIColor.black.cgColor]
gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
gradientLayer.endPoint = .init(x: 0, y: 1)
gradientLayer.zPosition = 1
gradientLayer.opacity = 0.5
layer.addSublayer(gradientLayer)
}
override func layoutSubviews() {
super.layoutSubviews()
gradientLayer.frame = bounds
}
}
I'm trying to draw a line in my MacOS app but I do not see the line. What can be a problem?
My code looks like:
func addLine() {
let path = NSBezierPath()
path.move(to: NSPoint(x: 100.0, y: 100))
path.line(to: NSPoint(x: 200.0, y: 200.0))
NSColor.green.setFill()
NSColor.green.setStroke()
path.close()
path.stroke()
}
And I call it in:
override func viewDidLoad() {
super.viewDidLoad()
addLine()
}
Am I doing something wrong? I just do not see anything in my window.
Have you created your own subclass of a NSView?
If I create a new view and add your code like so:
import Cocoa
class MyView: NSView {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
addLine()
}
func addLine() {
let path = NSBezierPath()
path.move(to: NSPoint(x: 100.0, y: 100))
path.line(to: NSPoint(x: 200.0, y: 200.0))
NSColor.green.setFill()
NSColor.green.setStroke()
path.close()
path.stroke()
}
}
And I then - in a storyboard - drag a "Custom View" to the canvas, change the type of the view to be MyView like so
Then I see this when running the app:
If you prefer to add the view in code, you can do something like this:
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
let myView = MyView()
myView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(myView)
myView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
myView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
myView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
myView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
}
}
So, your code seems to work, I'm just not sure how you are trying to use it.
Hope that gives you something to continue with.