Auto Resizing CAShapeLayer while Animating UIView - ios

Apologies, if this question has already been answered elsewhere. I tried searching in multiple places but could not find a good solution. I am a beginner to Swift development.
As per the code below, I am creating a SubView, adding an oval ShapeLayer to it and then animating the SubView by moving its center and increasing its size.
The SubView is animating correctly, however the ShapeLayer inside the SubView is not changing size. I would like the Red Oval to increase in size, similar to the SubView. I would really appreciate it if could let me know what I am missing.
class playGroundView: UIView {
override func draw(_ rect: CGRect) {
// Add a blue rectangle as subview
let startFrame = CGRect(x: self.frame.midX, y: self.frame.midY, width: 10, height: 20)
self.addSubview(UIView(frame: startFrame))
self.subviews[0].backgroundColor = UIColor.blue
// Create red oval shape that is bounded by blue rectangle
// Add red oval shape as sub-layer to blue rectangle view
let subView = self.subviews[0]
let ovalSymbol = UIBezierPath(ovalIn: subView.bounds)
let shapeLayer = CAShapeLayer()
shapeLayer.path = ovalSymbol.cgPath
shapeLayer.fillColor = UIColor.red.cgColor
shapeLayer.strokeColor = UIColor.red.cgColor
subView.layer.addSublayer(shapeLayer)
// Animate movement and increase in size of blue rectangle view
UIViewPropertyAnimator.runningPropertyAnimator(withDuration: 3, delay: 0, options: [], animations: {
let endFrame = CGRect(x:self.frame.midX - 50, y:self.frame.midY - 50, width: 20, height: 40)
self.subviews[0].frame = endFrame
self.setNeedsLayout()
self.layoutIfNeeded()
})
}
}
Image of Incorrect Output

Ok, after spending more time researching and getting a better understanding of what goes inside a ViewController and UIView class, entering the following in those classes works for me:
Inside class ViewController: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
let startFrame = CGRect(x: playGround.frame.midX, y: playGround.frame.midY, width: 30, height: 60)
cardSubView = cardView(frame: startFrame)
playGround.addSubview(cardSubView!)
let endFrame = CGRect(x: playGround.frame.midX - 100, y: playGround.frame.midY - 100, width: 60, height: 120)
UIViewPropertyAnimator.runningPropertyAnimator(withDuration: 10, delay: 0, options: [], animations: {
self.cardSubView?.frame = endFrame
self.cardSubView?.layoutIfNeeded()
})
}
Inside a UIView class:
class cardView: UIView {
override func draw(_ rect: CGRect) {
let backGroundPath = UIBezierPath(rect: rect)
UIColor.blue.setFill()
backGroundPath.fill()
let ovalSymbol = UIBezierPath(ovalIn: rect)
UIColor.red.setFill()
ovalSymbol.fill()
}
}
This still results in a weird frame shadowing towards the end of the animation in my iPhone simulator, however when running on device there is no issue.

Related

how to programmatically show a colored disk behind a UIImageView, in swift on an iOS device

I have an icon that I programmatically display.
How can I display a solid, colored disk behind the icon, at the same screen position?
Icon is opaque.
I will sometimes programmatically change screen position and disk's diameter and color.
Here's how I programmatically display the icon now.............
DispatchQueue.main.async
{
ViewController.wrist_band_UIImageView.frame = CGRect( x: screen_position_x,
y: screen_position_y,
width: App_class.screen_width,
height: App_class.screen_height)
}
UPDATE #1 for D.Mika below...
UPDATE #2 for D.Mika below...
import UIKit
import Foundation
class ViewController: UIViewController
{
static var circleView: UIView!
static let wrist_band_UIImageView: UIImageView = {
let theImageView = UIImageView()
theImageView.image = UIImage( systemName: "applewatch" )
theImageView.translatesAutoresizingMaskIntoConstraints = false
return theImageView
}()
override func viewDidLoad()
{
super.viewDidLoad()
view.addSubview( ViewController.wrist_band_UIImageView )
// Init disk image:
ViewController.circleView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 100.0, height: 100.0))
ViewController.circleView.backgroundColor = .red
ViewController.circleView.layer.cornerRadius = view.bounds.size.height / 2.0
ViewController.circleView.clipsToBounds = true
// Add view to view hierarchy below image view
ViewController.circleView.insertSubview(view, belowSubview: ViewController.wrist_band_UIImageView)
App_class.display_single_wearable()
}
}
class App_class
{
static var is_communication_established = false
static var total_packets = 0
static func display_single_wearable()
{
ViewController.wrist_band_UIImageView.frame = CGRect(x: 0, y: 0,
width: 100, height: 100)
ViewController.circleView.frame = CGRect( x: 0,
y: 0,
width: 100,
height: 100)
ViewController.circleView.layer.cornerRadius = 100
}
static func process_location_xy(text_location_xyz: String)
{}
} // App_class
You can display a colored circle using the following view:
circleView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 100.0, height: 100.0))
circleView.backgroundColor = .red
circleView.layer.cornerRadius = view.bounds.size.height / 2.0
circleView.clipsToBounds = true
// Add view to view hierarchy below image view
view.insertSubview(circleView, belowSubview: wrist_band_UIImageView)
You can change it's position and size by applying a new frame. But you have to change the layer's cornerRadius accordingly.
This is a simple example in a playground:
Edit:
I've modified the sample code to add the view the view hierarchy.
BUT, you still need to adjust the circle's frame, when you modify the image view's frame. (and the cornerRadius accordingly). For example
DispatchQueue.main.async
{
ViewController.wrist_band_UIImageView.frame = CGRect( x: screen_position_x,
y: screen_position_y,
width: App_class.screen_width,
height: App_class.screen_height)
circleView.frame = CGRect( x: screen_position_x,
y: screen_position_y,
width: App_class.screen_width,
height: App_class.screen_height)
circleView.layer.cornerRadius = App_class.screen_width
}
And you need to add a variable to the viewController holding the reference to the circle view, like:
var circleView: UIView!
The following answer works.
The answers from d.mika above did not work. Plus, he was insulting. ;-)
// Show red circle
let circlePath = UIBezierPath(arcCenter: CGPoint(x: 200, y: 400), radius: CGFloat(40), startAngle: CGFloat(0), endAngle: CGFloat(Double.pi * 2), clockwise: true)
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath
// Change the fill color
shapeLayer.fillColor = UIColor.red.cgColor
// You can change the stroke color
shapeLayer.strokeColor = UIColor.red.cgColor
// You can change the line width
shapeLayer.lineWidth = 3.0
view.layer.addSublayer(shapeLayer)

IOS - How to create Facebook reaction bar with blur background?

Although it may not be the week to replicate some design of Facebook, I would like to be able to design my own version of the reaction indicator view below.
I have three UIImageViews lined in the same positions as above. The problem is that, unlike Facebook, the background color may change (i.e is on top of a UIBlurEffect) and therefore I am unable to set the border color to white.
I thought it would make sense to set the borderColor like so:
imageViewOne.layer.borderColor = UIColor.clear.cgColor
imageViewOne.layer.borderWidth = 2
However, the underlying imageViewTwo is displayed in the border instead of the background color.
So far, I have this:
Would appreciate some help/ideas on how to make this work - I'm thinking of masks but not sure whether a. this is the correct solution and b. how to achieve the desired effect. To clarify, I am not able to set the border color as a constant as it will change with the UIBlurEffect.
In my opinion, there are 2 way to resolve your problem.
Create and use clipped image for Wow and Love like below Love image.
Another way is using mask property of UIView. Creating a mask image and apply it for mask property.
Mask image looks like.
Code for applying mask.
let imvLoveMask = UIImageView.init(image: UIImage.init(named: "MASK_IMAGE_NAME"));
imvLoveMask.frame = CGRect.init(x: 0, y: 0, width: imvLove.frame.size.width, height: imvLove.frame.size.height);
imvLove.mask = imvLoveMask;
Both of 2 above way can help you achieve what you want in the question. Background of icons in below image is an UIVisualEffectView.
In my opinion, the first way with clipped image is better and faster because you don't need to apply mask for your imageView. But if you don't want to create a clipped image for some reason, you can use the second way.
For more detail, you can take a look at my demo repo
You need to clip part of the image in order to let underlying content be visible in the gaps between images. See playground sample.
Add smile_1, smile_2, smile_3 images to playground resources. I took emoji images from https://emojipedia.org/facebook/.
import UIKit
import PlaygroundSupport
class EmojiView: UIView {
var imageView = UIImageView()
var imageInset = UIEdgeInsets(top: 3.0, left: 3.0, bottom: 3.0, right: 3.0)
var shapeLayer = CAShapeLayer()
var overlap: CGFloat = 0.0 {
didSet {
self.updateShape()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: UIView
override func awakeFromNib() {
super.awakeFromNib()
self.setup()
}
override func layoutSubviews() {
super.layoutSubviews()
self.imageView.frame = UIEdgeInsetsInsetRect(self.bounds, self.imageInset)
self.shapeLayer.frame = self.bounds
self.updateShape()
}
// MARK: Private
private func setup() {
self.addSubview(self.imageView)
self.layer.mask = self.shapeLayer
}
private func updateShape() {
let frame = self.bounds
let path = UIBezierPath(rect: frame)
// Cut off part of the image if overlap more then > 0
if 0 < self.overlap {
path.usesEvenOddFillRule = true
path.append(UIBezierPath(ovalIn: CGRect(x: -frame.width + self.overlap, y: 0.0, width: frame.width, height: frame.height)).reversing())
}
self.shapeLayer.path = path.cgPath
}
}
let overlap: CGFloat = 10 // Amount of pixels emojis overlap each other
// Create emoji views
let emojiView_1 = EmojiView(frame: CGRect(x: 5.0, y: 5.0, width: 40.0, height: 40.0))
emojiView_1.imageView.image = UIImage(named: "smile_1")
let emojiView_2 = EmojiView(frame: CGRect(x: emojiView_1.frame.maxX - overlap, y: 5.0, width: 40.0, height: 40.0))
emojiView_2.imageView.image = UIImage(named: "smile_2")
emojiView_2.overlap = overlap
let emojiView_3 = EmojiView(frame: CGRect(x: emojiView_2.frame.maxX - overlap, y: 5.0, width: 40.0, height: 40.0))
emojiView_3.imageView.image = UIImage(named: "smile_3")
emojiView_3.overlap = overlap
let holderView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: emojiView_3.frame.maxX + 5, height: 50.0))
// Add gradient layer
let gradientLayer = CAGradientLayer()
gradientLayer.frame = holderView.bounds
gradientLayer.colors = [UIColor.red.cgColor, UIColor.green.cgColor]
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
holderView.layer.addSublayer(gradientLayer)
// Add emoji views
holderView.addSubview(emojiView_1)
holderView.addSubview(emojiView_2)
holderView.addSubview(emojiView_3)
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = holderView
use this :
self.imageViewOne.layer.cornerRadius = self.imageViewOne.layer.bounds.width/2
self.imageViewOne.layer.masksToBounds = true
Simple suggestion: As you are setting border color programatically, you have a control to change it, according to background color (if background color is solid (not a gradient)).
imageViewOne.layer.borderColor = imageViewOne.superview?.backgroundColor ?? UIColor.white
imageViewOne.layer.borderWidth = 2.0
Actually instead of masking, you can put your images in a view which has white background and round(set corner radius). Then you can put these views (which has white background and images in it) via settings their zPosition or on storyboard with view hierarchy.
I've prepared a little playground for you. You can see the result in the screenshot. I've put a view inside the containerViews instead you can use uiimageview etc. It's a bit ugly but solves your issue I guess it's up to you to decide how use it.
Here is the code, you can just copy and paste it to a new playground and test it.
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
var mainContainerView = UIView(frame: CGRect(x: 0, y: 0, width: 140, height: 80))
mainContainerView.backgroundColor = UIColor.white
var containerView = UIView(frame: CGRect(x: 0, y: 0, width: 80, height: 80))
containerView.backgroundColor = UIColor.white
containerView.layer.cornerRadius = containerView.frame.width / 2
var innerView = UIView(frame: CGRect(x: 10, y: 10, width: 60, height: 60))
innerView.backgroundColor = UIColor.red
innerView.layer.cornerRadius = innerView.frame.width / 2
containerView.addSubview(innerView)
var containerView2 = UIView(frame: CGRect(x: 60, y: 0, width: 80, height: 80))
containerView2.backgroundColor = UIColor.yellow
containerView2.layer.cornerRadius = containerView2.frame.width / 2
var innerView2 = UIView(frame: CGRect(x: 10, y: 10, width: 60, height: 60))
innerView2.backgroundColor = UIColor.green
innerView2.layer.cornerRadius = innerView2.frame.width / 2
containerView2.addSubview(innerView2)
containerView.layer.zPosition = 2
containerView2.layer.zPosition = 1
mainContainerView.addSubview(containerView)
mainContainerView.addSubview(containerView2)
PlaygroundPage.current.liveView = mainContainerView

Swift textfields without border

I am new to swift. Your help will be really appreciated.
I have two textfields in my application. How would I create same UI as given in the pic below.
I want to create textfields with only one below border as given in the screenshot.
https://www.dropbox.com/s/wlizis5zybsvnfz/File%202017-04-04%2C%201%2052%2024%20PM.jpeg?dl=0
#IBOutlet var textField: UITextField! {
didSet {
let border = CALayer()
let width: CGFloat = 1 // this manipulates the border's width
border.borderColor = UIColor.darkGray.cgColor
border.frame = CGRect(x: 0, y: textField.frame.size.height - width,
width: textField.frame.size.width, height: textField.frame.size.height)
border.borderWidth = width
textField.layer.addSublayer(border)
textField.layer.masksToBounds = true
}
}
Create a subclass of UITextField so you can reuse this component across multiple views without have to re implement the drawing code. Expose various properties via #IBDesignable and #IBInspectable and you can have control over color and thickness in the story board. Also - implement a "redraw" on by overriding layoutSubviews so the border will adjust if you are using auto layout and there is an orientation or perhaps constraint based animation. That all said - effectively your subclass could look like this:
import UIKit
class Field: UITextField {
private let border = CAShapeLayer()
#IBInspectable var color: UIColor = UIColor.blue {
didSet {
border.strokeColor = color.cgColor
}
}
#IBInspectable var thickness: CGFloat = 1.0 {
didSet {
border.lineWidth = thickness
}
}
override func draw(_ rect: CGRect) {
self.borderStyle = .none
let from = CGPoint(x: 0, y: rect.height)
let here = CGPoint(x: rect.width, y: rect.height)
let path = borderPath(start: from, end: here).cgPath
border.path = path
border.strokeColor = color.cgColor
border.lineWidth = thickness
border.fillColor = nil
layer.addSublayer(border)
}
override func layoutSubviews() {
super.layoutSubviews()
let from = CGPoint(x: 0, y: bounds.height)
let here = CGPoint(x: bounds.width, y: bounds.height)
border.path = borderPath(start: from, end: here).cgPath
}
private func borderPath(start: CGPoint, end: CGPoint) -> UIBezierPath {
let path = UIBezierPath()
path.move(to: start)
path.addLine(to: end)
return path
}
}
Then when you add a text field view to your story board - update the class in the Identity Inspector to use this subclass, Field - and then in the attributes inspector, you can set color and thickness.
Add border at Bottom in UITextField call below function:
func setTextFieldBorder(_ dimension: CGRect) -> CALayer {
let border = CALayer()
let width = CGFloat(2.0)
border.borderColor = UIColor.darkGray.cgColor
border.frame = CGRect(x: 0, y: dimension.size.height - width, width: dimension.size.width, height: dimension.size.height)
border.borderWidth = width
return border
}
How to set UITextField border in textField below sample code for that:
txtDemo.layer.addSublayer(setTextFieldBorder(txtDemo.frame))
txtDemo.layer.masksToBounds = true
Where txtDemo is IBOutlet of UITextField.

Centering a CAShapeLayer within a UIView?

There are probably more than 5 questions just like this one, but none of them solve the problem.
I want to center a circle on a view. It's not happening despite trying all kinds of methods through similar questions like this one.
I'm not sure if this happens because I set the translatesAutoresizingMaskIntoConstraints = false. I tried playing around with the center and anchor points of the shape layer but crazy behavior happens. I tried putting this code in viewDidLayouSubviews. Didn't work. What else can I do?
colorSizeGuide is the view of which I'm trying to center my layer in.
func setupConstraints() {
// other constraints set up here
colorSizeGuide.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
colorSizeGuide.topAnchor.constraint(equalTo: view.topAnchor, constant: 30).isActive = true
colorSizeGuide.widthAnchor.constraint(equalToConstant: 30).isActive = true
colorSizeGuide.heightAnchor.constraint(equalToConstant: 30).isActive = true
}
func setupColorSizeGuide() {
shape.path = UIBezierPath(ovalIn: colorSizeGuide.frame).cgPath
shape.position = self.colorSizeGuide.center
shape.anchorPoint = CGPoint(x: 0.5, y: 0.5)
shape.strokeColor = (UIColor.black).cgColor
shape.fillColor = (UIColor.clear).cgColor
shape.lineWidth = 1.0
colorSizeGuide.layer.addSublayer(shape)
}
There are a few options you can do.
If you're not in a scrolling environment (e.g. tableView) use corner radius of half of the width of the rectangle on the view, then the view will be cropped to a circle - this is not particularly fast or customizable, but it gets the job done.
Playground Code:
import UIKit
import PlaygroundSupport
let frame: CGRect = CGRect(x: 0, y: 0, width: 100, height: 100)
let view: UIView = UIView(frame: frame)
view.backgroundColor = .magenta
view.layer.cornerRadius = frame.size.width / 2
PlaygroundPage.current.liveView = view
You can make your custom UIView subclass implement the layerClass method and return CAShapeLayer there. This will mean that self.layer of your view will actually be a shape layer. You can set a path of a circle there and there you go. If you want to center it in a view just make sure to use bounds coordinates of the view when defining the UIBezierPath.
Playground code:
import UIKit
import PlaygroundSupport
let frame: CGRect = CGRect(x: 0, y: 0, width: 100, height: 100)
let view: UIView = UIView(frame: frame)
PlaygroundPage.current.liveView = view
class ShapeView: UIView {
override class var layerClass: AnyClass { return CAShapeLayer.self }
override init(frame: CGRect) {
super.init(frame: frame)
(layer as? CAShapeLayer)?.fillColor = UIColor.red.cgColor
(layer as? CAShapeLayer)?.strokeColor = UIColor.green.cgColor
(layer as? CAShapeLayer)?.path = UIBezierPath(ovalIn: frame).cgPath
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
let sv = ShapeView(frame: frame)
view.addSubview(sv)
Make a non-view shape layer, by doing CAShapeLayer.init. Position your on your view in its layoutSubviews method (or viewDidLayoutSubviews if you're doing it in the view controller) and set a proper frame to the shape layer, like it was a view.
Playground Code:
import UIKit
import PlaygroundSupport
let frame: CGRect = CGRect(x: 0, y: 0, width: 100, height: 100)
let smallFrame: CGRect = CGRect(x: 0, y: 0, width: 10, height: 10)
let view: UIView = UIView(frame: frame)
view.backgroundColor = .magenta
PlaygroundPage.current.liveView = view
let sl = CAShapeLayer()
sl.path = UIBezierPath(ovalIn: smallFrame).cgPath
sl.fillColor = UIColor.red.cgColor
sl.strokeColor = UIColor.green.cgColor
sl.frame.origin.x = 30
sl.frame.origin.y = 30
view.layer.addSublayer(sl)

UITableViewCell drawRect bottom border disappears on insertRow

I have a custom UITableViewCell where I use drawRect to paint a simple bottom border:
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
CGContextMoveToPoint(context, CGRectGetMinX(rect), CGRectGetMaxY(rect))
CGContextAddLineToPoint(context, CGRectGetMaxX(rect), CGRectGetMaxY(rect))
CGContextSetStrokeColorWithColor(context, UIColor(netHex: 0xEFEEF4).CGColor)
CGContextSetLineWidth(context, 2)
CGContextStrokePath(context)
}
This works perfectly. However when I insert a row with animation the borders of ALL cells disappear and appear again when insert animation finishes:
tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: cells.count - 1, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Fade)
Any idea how to avoid this?
Well You can try this code in tablecell's awakeFromNib if you only want to use CALayers assuming that your TableView is covering the full width of the device.
override func awakeFromNib() {
super.awakeFromNib()
let borderLayer = CALayer()
let lineHeight:CGFloat = 2
borderLayer.frame = CGRect(x: 0, y: self.frame.height - lineHeight , width: UIScreen.mainScreen().bounds.width, height: lineHeight)
borderLayer.backgroundColor = UIColor.redColor().CGColor
self.layer.addSublayer(borderLayer)
}
and you will get the output as:
Also make your tableview separator color to clear
self.tableView.separatorColor = UIColor.clearColor()
So that it doesn't gets overlapped with your layer.
What I can observe that now no borders of cells disappears ever whenever a new row is inserted.
Alternatively
We can just use a UIImageView in the cell storyboard and provide a color with the following constraints.
Adding UIImageView
Adding Constraints to UIImageView
And we are done!
There is one more alternate solution to achieve this using Bezier Paths
override func awakeFromNib() {
super.awakeFromNib()
let line = CAShapeLayer()
let linePath = UIBezierPath()
linePath.moveToPoint(CGPointMake(0, self.frame.height))
linePath.addLineToPoint(CGPointMake(UIScreen.mainScreen().bounds.width, self.frame.height))
line.lineWidth = 3.0
line.path = linePath.CGPath
line.strokeColor = UIColor.redColor().CGColor
self.layer.addSublayer(line)
}
This also yields the same output.
EDIT:
If we are not using storyboards or nibs for the cell and creating the cell programatically, then we can do a workaround like this:
Create a property in your CustomTableViewCell class
var borderLayer:CALayer!
Now there is a method called layoutSubviews in CustomTableViewCell class
override func layoutSubviews() {
if(borderLayer != nil) {
borderLayer.removeFromSuperlayer()
}
borderLayer = CALayer()
let lineHeight:CGFloat = 2
borderLayer.frame = CGRect(x: 0, y: self.frame.height - lineHeight , width: UIScreen.mainScreen().bounds.width, height: lineHeight)
borderLayer.backgroundColor = UIColor.redColor().CGColor
self.layer.addSublayer(borderLayer)
}
Try this out.
It's not direct answer, just my suggestion how to achieve equal visual result without drawing.
See example code and result image
#IBOutlet weak var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
let layer = CALayer()
let lineHeight:CGFloat = 2
layer.frame = CGRect(x: 0, y: button.bounds.height - lineHeight , width: button.bounds.width, height: lineHeight)
layer.backgroundColor = UIColor(colorLiteralRed: 0xEF/255.0, green: 0xEE/255.0, blue: 0xF4/255.0, alpha: 1).CGColor
button.layer.addSublayer(layer)
}
Button and background view colors configured in IB.

Resources