Centering an Oval using CGRectMake Swift - ios

I am having trouble trying to center my oval programmatically currently I have this code
func setupLayers(){
let oval = CAShapeLayer()
oval.frame = CGRectMake(137.5, 283.5, 100, 100)
oval.path = ovalPath().CGPath;
self.layer.addSublayer(oval)
layers["oval"] = oval
resetLayerPropertiesForLayerIdentifiers(nil)
}
This code is able to center the oval in an iPhone 6 and 6s, but I want it to be able to be centered in all devices.
I have tried this code too:
func drawCircle(size: CGFloat) {
let circleShape = CAShapeLayer()
circleShape.path = UIBezierPath(ovalInRect: CGRectMake(-size/2, -size/2, size, size)).CGPath
circleShape.fillColor = UIColor.blueColor().CGColor
circleShape.strokeColor = UIColor.redColor().CGColor
circleShape.lineWidth = 1
circleShape.frame.origin = view.center
circleShape.name = "circleShape"
view.layer.addSublayer(circleShape)
}
drawCircle(100)

You need to set the layer's anchorPoint to be its center.
oval.anchorPoint = CGPoint(x: 0.5, y: 0.5)
Then you can set position of layer as the center of view:
oval.position = self.center

Related

How to create a solid rectangle border around the circle in UICollectionView Swift4+

I have tried the following but only creates a border around the circle but not a separate rectangle border.
as shown here
cell.layer.borderWidth = 1.0
cell.layer.borderColor = UIColor.black.cgColor
I want to create a rectangle border as shown here
Instead of
cell.layer.borderWidth = 1.0
cell.layer.cornerRadius = 10
cell.layer.borderColor = UIColor.black.cgColor
Have you tried?
cell.layer.borderWidth = 1.0
cell.layer.borderColor = UIColor.black.cgColor
I'm not sure if it'll work for you, but you can try to add an additional layer like that:
var rect = UIView()
var circle: CALayer?
override func loadView() {
// create view with border
rect.frame = CGRect(x: 50, y: 50, width: 300, height: 200)
rect.layer.borderColor = UIColor.black.cgColor
rect.layer.backgroundColor = UIColor.clear.cgColor
rect.layer.borderWidth = 2
// add circle layer
let circle = CALayer()
circle = UIColor.red.cgColor
// add circle layer on view with drawn border
rect.layer.addSublayer(circle)
view.addSubview(rect)
circle = circle
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// layout circle on your view
let radius = min(rect.frame.width, rect.frame.height) * 0.5
circle?.frame = CGRect(x: rect.bounds.width / 2 - radius / 2, y: rect.bounds.height / 2 - radius / 2, width: radius, height: radius)
circle?.cornerRadius = radius / 2
}
But probably that's not the best option, maybe someone gives you better solution.
If it doesn't work for you, please, give more details of you problem.

How to cut portion of CALayer in iOS Swift? [duplicate]

This question already has answers here:
How can I 'cut' a transparent hole in a UIImage?
(4 answers)
Closed 3 years ago.
I am trying to create a QR Reader. For that I am showing a rectOfInterest with some CALayer for visual representation. I want to show a box with some border at the corners and black background with some opacity so hide the other view from the AVCaptureVideoPreviewLayer. What I have achieved till now looks like this:
As you can see the CALayer is there but I want to cut the box portion of the layer so that that blackish thing does not come there. The code I am using to do this is like below:
func createTransparentLayer()->CALayer{
let shape = CALayer()
shape.frame = self.scanView.layer.bounds
shape.backgroundColor = UIColor.black.cgColor
shape.opacity = 0.7
return shape
}
I looked into other questions for this, seems like you have the mask the layer with the cut portion. So I subclassed the CALayer and cleared the context in drawInContext and set the mask property of the super layer to this. After that I get nothing. Everything is invisible there. What is wrong in this?
The code I tried is this:
class TransparentLayer: CALayer {
override func draw(in ctx: CGContext) {
self.backgroundColor = UIColor.black.cgColor
self.opacity = 0.7
self.isOpaque = true
ctx.clear(CGRect(x: superlayer!.frame.size.width / 2 - 100, y: superlayer!.frame.size.height / 2 - 100, width: 200, height: 200))
}
}
then set the mask property like this:
override func viewDidLayoutSubviews() {
self.rectOfInterest = CGRect(x: self.scanView.layer.frame.size.width / 2 - 100, y: self.scanView.layer.frame.size.height / 2 - 100, width: 200, height: 200)
scanView.rectOfInterest = self.rectOfInterest
let shapeLayer = self.createFrame()
scanView.doInitialSetup()
self.scanView.layer.mask = self.createTransparentLayer()
self.scanView.layer.addSublayer(shapeLayer)
}
here the shapeLayer is the bordered corner in the screenshot. How can I achieve this?
I have added view in my view controller which is centre align vertically and horizontally. Also fixed height and width to 200. Then created extension of UIView and added following code:
extension UIView {
func strokeBorder() {
self.backgroundColor = .clear
self.clipsToBounds = true
let maskLayer = CAShapeLayer()
maskLayer.frame = bounds
maskLayer.path = UIBezierPath(rect: self.bounds).cgPath
self.layer.mask = maskLayer
let line = NSNumber(value: Float(self.bounds.width / 2))
let borderLayer = CAShapeLayer()
borderLayer.path = maskLayer.path
borderLayer.fillColor = UIColor.clear.cgColor
borderLayer.strokeColor = UIColor.white.cgColor
borderLayer.lineDashPattern = [line]
borderLayer.lineDashPhase = self.bounds.width / 4
borderLayer.lineWidth = 10
borderLayer.frame = self.bounds
self.layer.addSublayer(borderLayer)
}
}
Use:
By using outlet of view and call method to set border as you have request.
self.scanView.strokeBorder()
To clear the backgroundColor respective to mask view, I have added following code to clear it.
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.scanView.strokeBorder()
self.backgroundView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
// Draw a graphics with a mostly solid alpha channel
// and a square of "clear" alpha in there.
UIGraphicsBeginImageContext(self.backgroundView.bounds.size)
let cgContext = UIGraphicsGetCurrentContext()
cgContext?.setFillColor(UIColor.white.cgColor)
cgContext?.fill(self.backgroundView.bounds)
cgContext?.clear(CGRect(x:self.scanView.frame.origin.x, y:self.scanView.frame.origin.y, width: self.scanView.frame.width, height: self.scanView.frame.height))
let maskImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// Set the content of the mask view so that it uses our
// alpha channel image
let maskView = UIView(frame: self.backgroundView.bounds)
maskView.layer.contents = maskImage?.cgImage
self.backgroundView.mask = maskView
}
Output:
I'm not using camera in background.

UIButton with gradient border and rounded corners

What I am trying to get is the a custom UIButton that has a gradient border (just the border is gradient) and rounded corners. I almost got to where I wanted to be, but having issues with the corners.
Here is what I currently have:
Here is my code:
override func viewDidLoad() {
super.viewDidLoad()
let gradient = CAGradientLayer()
gradient.frame = CGRect(origin: CGPoint.zero, size: self.myButton.frame.size)
gradient.colors = [UIColor.blue.cgColor, UIColor.green.cgColor]
gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
gradient.cornerRadius = 15
let shape = CAShapeLayer()
shape.lineWidth = 5
shape.path = UIBezierPath(rect: self.myButton.bounds).cgPath
shape.strokeColor = UIColor.black.cgColor
shape.fillColor = UIColor.clear.cgColor
shape.cornerRadius = 15
gradient.mask = shape
self.myButton.clipsToBounds = true
self.myButton.layer.cornerRadius = 15
self.myButton.layer.addSublayer(gradient)
}
So the question is how do I display corners with gradient?
The problem is with the mask, try to remove shape.cornerRadius = 15 and change this:
shape.path = UIBezierPath(rect: self.myButton.bounds).cgPath
to this:
shape.path = UIBezierPath(roundedRect: self.myButton.bounds.insetBy(dx: 2.5, dy: 2.5), cornerRadius: 15.0).cgPath
Play with the values of the insets and cornerRadius to achieve your desired result.

Thin border when using CAShapeLayer as mask for CAShapeLayer

In Swift, I have two semi-transparent circles, both of which are CAShapeLayer. Since they are semi-transparent, any overlap between them becomes visible like so:
Instead, I want them to visually "merge" together. The solution I have tried is to use circle 2 as a mask for circle 1, therefore cutting away the overlap.
This solution is generally working, but I get a thin line on the outside of circle 2:
My question: How can I get rid of the thin, outside line on the right circle? Why is it even there?
The code is as follows (Xcode playground can be found here):
private let yPosition: CGFloat = 200
private let circle1Position: CGFloat = 30
private let circle2Position: CGFloat = 150
private let circleDiameter: CGFloat = 200
private var circleRadius: CGFloat { return self.circleDiameter/2.0 }
override func loadView() {
let view = UIView()
view.backgroundColor = .black
self.view = view
let circle1Path = UIBezierPath(
roundedRect: CGRect(
x: circle1Position,
y: yPosition,
width: circleDiameter,
height: circleDiameter),
cornerRadius: self.circleDiameter)
let circle2Path = UIBezierPath(
roundedRect: CGRect(
x: circle2Position,
y: yPosition,
width: circleDiameter,
height: circleDiameter),
cornerRadius: self.circleDiameter)
let circle1Layer = CAShapeLayer()
circle1Layer.path = circle1Path.cgPath
circle1Layer.fillColor = UIColor.white.withAlphaComponent(0.6).cgColor
let circle2Layer = CAShapeLayer()
circle2Layer.path = circle2Path.cgPath
circle2Layer.fillColor = UIColor.white.withAlphaComponent(0.6).cgColor
self.view.layer.addSublayer(circle1Layer)
self.view.layer.addSublayer(circle2Layer)
//Create a mask from the surrounding rectangle of circle1, and
//then cut out where it overlaps circle2
let maskPath = UIBezierPath(rect: CGRect(x: circle1Position, y: yPosition, width: circleDiameter, height: circleDiameter))
maskPath.append(circle2Path)
maskPath.usesEvenOddFillRule = true
maskPath.lineWidth = 0
let maskLayer = CAShapeLayer()
maskLayer.path = maskPath.cgPath
maskLayer.fillColor = UIColor.black.cgColor
maskLayer.fillRule = kCAFillRuleEvenOdd
circle1Layer.mask = maskLayer
}
If both CAShapeLayers have the same alpha value, you could place them inside a new parent CALayer then set the alpha of the parent instead.

Positioning layers of uiview in swift

I am working on a timeline view. I am drawing a line in the centre of my icon and drawing a circle with fill colour. But the problem is that when I draw the circle, it is always on the top of the icon. Now the icon is not showing. I tried zposition of the layers. Here is what I tried
override func draw(_ rect: CGRect) {
if let anchor = anchorView(){
let centreRelativeToTableView = anchor.superview!.convert(anchor.center, to: self)
// print("Anchor x origin : \(anchor.frame.size.origin.x)")
timelinePoint.position = CGPoint(x: centreRelativeToTableView.x , y: centreRelativeToTableView.y/2)
timeline.start = CGPoint(x: centreRelativeToTableView.x , y: 0)
timeline.middle = CGPoint(x: timeline.start.x, y: anchor.frame.origin.y)
timeline.end = CGPoint(x: timeline.start.x, y: self.bounds.size.height)
timeline.draw(view: self.contentView)
let circlePath = UIBezierPath(arcCenter: CGPoint(x: anchor.center.x,y: anchor.center.y - 20), radius: CGFloat(20), startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath
//change the fill color
shapeLayer.fillColor = UIColor.randomFlat.cgColor
// shapeLayer.fillColor = UIColor.clear.cgColor
//you can change the stroke color
shapeLayer.strokeColor = UIColor.white.cgColor
//you can change the line width
shapeLayer.lineWidth = 5
shapeLayer.zPosition = 0
anchor.alpha = 1
//Set Anchor Z position
anchor.layer.zPosition = 2
shapeLayer.zPosition = 1
anchor.layer.addSublayer(shapeLayer)
// Setting icon to layer
/*let imageLayer = CALayer()
imageLayer.contents = newImage
anchor.layer.addSublayer(imageLayer)*/
// timelinePoint.draw(view: self.contentView)
}else{
print("this should not happen")
}
}
-------
I want to draw my icon with white tint on top of the circle. Please help me
Using addSublayer will add the new layer on top, which will cover everything else added before.
If you know which layer your icon is at, you can instead use insertSublayer(at:) to place it under your icon
Alternatively you can create another UIView with the exact frame of the icon in storyboard and place it lower in the hierarchy so whatever your draw ends up under.

Resources