Shadow left and right of UIView - iphone

Hi i like to add an CALayer Shadow to an View where the shadow was left and right of the view the simplest way was:
someView.layer.shadowColor = [[UIColor blackColor] CGColor];
someView.layer.shadowOffset = CGSizeMake(0.0f,0.0f);
someView.layer.shadowOpacity = 1.0f;
someView.layer.shadowRadius = 10.0f;
someView.layer.shadowPath = [[UIBezierPath bezierPathWithRect:someView.bounds] CGPath];
but i will add a bigger shadow as like a shadow when i increase the shadowRadius it do not look good. How i can make a shadow that looks good at left and right.

I think 10 is a pretty big shadow radius, try 3 or 4 instead, also opacity I usually use 0.7:
someView.layer.shadowColor = [[UIColor blackColor] CGColor];
someView.layer.shadowOffset = CGSizeMake(0.0f,0.0f);
someView.layer.shadowOpacity = 0.7f;
someView.layer.shadowRadius = 4.0f;
If you want the shadow only on left and right, then inset the rectangle on the top and bottom so the top and bottom shadow are hidden behind your view:
CGRect shadowRect = CGRectInset(someView.bounds, 0, 4); // inset top/bottom
someView.layer.shadowPath = [[UIBezierPath bezierPathWithRect:shadowRect] CGPath];
I'm not really sure if that's what you wanted.

swift 3.0 version
imageView.layer.shadowOpacity = 0.8
imageView.layer.shadowOffset = CGSize(width: 0, height: 3)
imageView.layer.shadowRadius = 4.0
let shadowRect: CGRect = imageView.bounds.insetBy(dx: 0, dy: 4)
imageView.layer.shadowPath = UIBezierPath(rect: shadowRect).cgPath

progrmr's answer was very helpful, cheers!
I made a slide-out menu and I had a problem with the shadow surrounding my VC and disrupting the navigation bar. Turned out I had to inset the shadow layer.
Here's my solution using swift:
rightViewController!.view.layer.shadowOpacity = 0.8
rightViewController!.view.layer.shadowOffset = CGSizeMake(0, 3)
rightViewController!.view.layer.shadowRadius = 4.0
let shadowRect: CGRect = CGRectInset(rightViewController!.view.bounds, 0, 4); // inset top/bottom
rightViewController!.view.layer.shadowPath = UIBezierPath(rect: shadowRect).CGPath

I created a shadow that can be used at the top/bottom or left/right, without prejudice at all. No shadow will appear in the left/right if you choose top/bottom, and so on. I hope I helped. Here's the code:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let imgView = UIImageView(frame: CGRect(x: self.view.bounds.midX - 150, y: self.view.bounds.midY - 150, width: 300, height: 300))
imgView.contentMode = .scaleToFill
imgView.image = UIImage(named: "name image")
self.view.addSubview(imgView)
//You can put left/right or top/bottom
imgView.addShadow(sides: .leftRight, constant: 10, alpha: 5)
}
}
extension UIView{
func addShadow(sides: Sides, constant: Int, alpha: Int){
if(constant > 0 && alpha > 0){
switch sides {
case .leftRight:
let view = UIView(frame: CGRect(x: -CGFloat(constant), y: 0, width: self.bounds.width + CGFloat((constant * 2)), height: self.bounds.height))
self.addSubview(view)
addMask(sides: .leftRight, view: view, constant: constant, shadowRadius: alpha)
case .topBottom:
let view = UIView(frame: CGRect(x: 0, y: -CGFloat(constant), width: self.bounds.width , height: self.bounds.height + CGFloat(constant * 2)))
self.addSubview(view)
addMask(sides: .topBottom, view: view, constant: constant, shadowRadius: alpha)
}
}
}
private func addMask(sides:Sides, view: UIView, constant: Int, shadowRadius:Int){
let mutablePath = CGMutablePath()
let mask = CAShapeLayer()
switch sides {
case .leftRight:
mutablePath.addRect(CGRect(x: -CGFloat(constant), y: 0, width: view.bounds.width, height: view.bounds.height))
mutablePath.addRect(CGRect(x: CGFloat(constant) , y: 0, width: view.bounds.width , height: view.bounds.height))
case .topBottom:
mutablePath.addRect(CGRect(x: 0, y: -CGFloat(constant), width: view.bounds.width, height: view.bounds.height))
mutablePath.addRect(CGRect(x: 0, y: CGFloat(constant) , width: view.bounds.width , height: view.bounds.height))
}
mask.path = mutablePath
mask.fillRule = CAShapeLayerFillRule.evenOdd
mask.fillColor = UIColor(white:1.0, alpha: 0.2).cgColor
view.layer.mask = mask
view.layer.addSublayer(mask)
mask.shadowColor = UIColor.black.cgColor
mask.shadowRadius = CGFloat(shadowRadius)
mask.shadowOpacity = 1.0
mask.shadowOffset = CGSize(width: 0, height: 0)
}
}
enum Sides{
case leftRight
case topBottom
}
You just need to call the extension UIView, which has the addShadow() function and pass the parameters you want.

Related

Wrong size of gradient border on image after fast scroll on tvOS

I have an app on tvOS and collection view with horizontal scroll. When the item is focused the ImageView grows a bit. I also added gradient border to focused ImageView inside this cellView. I'm adding gradient border based on this answer https://stackoverflow.com/a/62091073/4037291
public extension UIView {
private static let kLayerNameGradientBorder = "GradientBorderLayer"
func gradientBorder(width: CGFloat,
colors: [UIColor],
startPoint: CGPoint = CGPoint(x: 0.5, y: 0.0),
endPoint: CGPoint = CGPoint(x: 0.5, y: 1.0),
andRoundCornersWithRadius cornerRadius: CGFloat = 0) {
let existingBorder = gradientBorderLayer()
let border = existingBorder ?? CAGradientLayer()
border.frame = CGRect(x: bounds.origin.x, y: bounds.origin.y,
width: bounds.size.width + width, height: bounds.size.height + width)
border.colors = colors.map { return $0.cgColor }
border.startPoint = startPoint
border.endPoint = endPoint
let mask = CAShapeLayer()
let maskRect = CGRect(x: bounds.origin.x + width/2, y: bounds.origin.y + width/2,
width: bounds.size.width - width, height: bounds.size.height - width)
mask.path = UIBezierPath(roundedRect: maskRect, cornerRadius: cornerRadius).cgPath
mask.fillColor = UIColor.clear.cgColor
mask.strokeColor = UIColor.white.cgColor
mask.lineWidth = width
border.mask = mask
let exists = (existingBorder != nil)
if !exists {
layer.addSublayer(border)
}
}
private func gradientBorderLayer() -> CAGradientLayer? {
let borderLayers = layer.sublayers?.filter { return $0.name == UIView.kLayerNameGradientBorder }
if borderLayers?.count ?? 0 > 1 {
fatalError()
}
return borderLayers?.first as? CAGradientLayer
}
}
In general it works fine but sometimes when I scroll fast the border doesn't reflect size of the view.
The image bellow shows how the border looks when I scroll fast.
I'm adding gradient border to and image like this.
view.logoView.addGradientBorder(
width: 4,
colors: AppTheme.Color.gradient,
startPoint: .topLeft,
endPoint: .bottomRight,
andRoundCornersWithRadius: 4
)
The borders should be around image even after fast scroll.
Thank you for your help.

How to make the uiview not move after setting its layer's anchorPoint under Autolayout

I have a requirement that need change the UIView layer's anchorPoint, but the view cannot be moved after changing anchorPoint.
I know it is possible when the view is defined by frame(CGRect:...). like this:
let width = SCREEN_WIDTH - 40
let view2 = UIView(frame: CGRect(x: 20, y: 300, width: width, height: 200))
view2.backgroundColor = .blue
self.view.addSubview(view2)
let oldFrame2 = view2.frame
view2.layer.anchorPoint = CGPoint(x: 0, y: 0.5)
view2.frame = oldFrame2
This works.
But my view is defined by Autolayout, I try the solution like above code, but it doesn't work. Code:
let view1 = UIView()
view1.backgroundColor = .orange
self.view.addSubview(view1)
view1.snp.makeConstraints { (maker) in
maker.top.equalToSuperview().offset(50)
maker.leading.equalToSuperview().offset(20)
maker.trailing.equalToSuperview().offset(-20)
maker.height.equalTo(200)
}
let oldFrame1 = view1.frame
view1.layer.anchorPoint = CGPoint(x: 0, y: 0.5)
view1.frame = oldFrame1
The result is: the orange view1 be moved, it should be like the blue view2 after changing anchorPoint.
So can anyone give me some suggestions?
------------------------------Update Answer-----------------------------
Just as #DonMag answer, we can implement this requirement by updating the constraints of view not frame when using Autolayout. Here is the code by SnapKit:
let view1 = UIView()
view1.backgroundColor = .orange
view1.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(view1)
view1.snp.makeConstraints { (maker) in
maker.top.equalToSuperview().offset(100)
maker.leading.equalToSuperview().offset(20)
maker.trailing.equalToSuperview().offset(-20)
maker.height.equalTo(200)
}
// important!!!
view1.layoutIfNeeded()
let oldFrame1 = view1.frame
view1.layer.anchorPoint = CGPoint(x: 0, y: 0.5)
// update constraints by updateConstraints function
// if you use #IBOutlet NSLayoutConstraint from xib,
// you can also just set xxx.constant = yyy to update the constraints.
view1.snp.updateConstraints { (maker) in
let subOffset = oldFrame1.width * 0.5
maker.leading.equalToSuperview().offset(20 - subOffset)
maker.trailing.equalToSuperview().offset(-20 - subOffset)
}
let width = SCREEN_WIDTH - 40
let view2 = UIView(frame: CGRect(x: 20, y: 300, width: width, height: 200))
view2.backgroundColor = .blue
self.view.addSubview(view2)
let oldFrame2 = view2.frame
view2.layer.anchorPoint = CGPoint(x: 0, y: 0.5)
view2.frame = oldFrame2
Another solution is to change the autolayout view to frame by setting translatesAutoresizingMaskIntoConstraints = true, like this:
let width = SCREEN_WIDTH - 40
let view1 = UIView()
view1.backgroundColor = .orange
self.view.addSubview(view1)
// Autolayout
view1.snp.makeConstraints { (maker) in
maker.top.equalToSuperview().offset(100)
maker.leading.equalToSuperview().offset(20)
maker.trailing.equalToSuperview().offset(-20)
maker.height.equalTo(200)
}
// change autolayout to frame
view1.translatesAutoresizingMaskIntoConstraints = true
view1.frame = CGRect(x: 20, y: 100, width: width, height: 200)
let oldFrame1 = view1.frame
view1.layer.anchorPoint = CGPoint(x: 0, y: 0.5)
view1.frame = oldFrame1
let view2 = UIView(frame: CGRect(x: 20, y: 300, width: width, height: 200))
view2.backgroundColor = .blue
self.view.addSubview(view2)
let oldFrame2 = view2.frame
view2.layer.anchorPoint = CGPoint(x: 0, y: 0.5)
view2.frame = oldFrame2
First, when using auto-layout / constraints, setting the view's .frame directly will not give desired results. As soon as auto-layout updates the UI, the constraints will be re-applied.
When you change the .anchorPoint you change the geometry of the view. For that reason, you may be better off using .frame instead of auto-layout.
If you do need / want to use auto-layout, you'll need to update the .constant values of the constraints to account for the geometry changes.
I don't know how to do that with SnapKit, but here is an example using "standard" constraint syntax.
Declare Leading and Trailing constraint variables
assign and activate the constraints
tell auto-layout to calculate the frame
change the anchorPoint
update the Leading and Trailing constraint constants to reflect the geometry change
Note: this is example code only!:
class ViewController: UIViewController {
// these will have their .constant values changed
// to account for layer.anchorPoint change
var leadingConstraint: NSLayoutConstraint!
var trailingConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// NOT using auto-layout constraints
let width = view.frame.width - 40
let view2 = UIView(frame: CGRect(x: 20, y: 300, width: width, height: 200))
view2.backgroundColor = .blue
self.view.addSubview(view2)
let oldFrame2 = view2.frame
view2.layer.anchorPoint = CGPoint(x: 0, y: 0.5)
view2.frame = oldFrame2
// USING auto-layout constraints
let view1 = UIView()
view1.backgroundColor = .orange
view1.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(view1)
// create leading and trailing constraints
leadingConstraint = view1.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20.0)
trailingConstraint = view1.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20.0)
// activate constraints
NSLayoutConstraint.activate([
view1.topAnchor.constraint(equalTo: view.topAnchor, constant: 80.0),
view1.heightAnchor.constraint(equalToConstant: 200.0),
leadingConstraint,
trailingConstraint,
])
// auto-layout has not run yet, so force it to layout
// the view frame
view1.layoutIfNeeded()
// get the auto-layout generated frame
let oldFrame1 = view1.frame
// change the anchorPoint
view1.layer.anchorPoint = CGPoint(x: 0, y: 0.5)
// we've move the X anchorPoint from 0.5 to 0.0, so
// we need to adjust the leading and trailing constants
// by 0.5 * the frame width
leadingConstraint.constant -= oldFrame1.width * 0.5
trailingConstraint.constant -= oldFrame1.width * 0.5
}
}
Result:

Programmatically drawing custom oval shape on screen swift

How can i draw custom oval shape like in below image in swift (not swiftUI).
Thank you in advance
I have tried to clone similar view using UIView and was able to create similar UI as you have stated on screenshot
And here is my code snippet
let width: CGFloat = view.frame.size.width
let height: CGFloat = view.frame.size.height
let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: self.view.bounds.size.height), cornerRadius: 0)
let rect = CGRect(x: width / 2 - 150, y: height / 2.5 - 100, width: 300, height: 400)
let circlePath = UIBezierPath(ovalIn: rect)
path.append(circlePath)
path.usesEvenOddFillRule = true
let fillLayer = CAShapeLayer()
fillLayer.path = path.cgPath
fillLayer.fillRule = .evenOdd
fillLayer.fillColor = UIColor.red.cgColor
fillLayer.opacity = 0.5
view.layer.addSublayer(fillLayer)
Hope this helps you. Good day.
You can draw oval path like this
class CustomOval: UView {
override func drawRect(rect: CGRect) {
var ovalPath = UIBezierPath(ovalIn: rect)
UIColor.gray.setFill()
ovalPath.fill()
}
}

How do add a bottom boarder to UIView Class?

I have a view class that I apply to various UIViews in UITableViews throughout my Storyboard.
class ListContainerView: UIView {
override func awakeFromNib() {
super.awakeFromNib()
// Set the thickness of the border
let thickness: CGFloat = 0.5
// Set the color of the border
let color: CGColor = UIColor.lightGray.cgColor
// Add top border to the ListContainerView
let topBorder = CALayer()
topBorder.frame = CGRect(x: 0.0, y: 0.0, width: self.frame.size.width, height: thickness)
topBorder.backgroundColor = color
self.layer.addSublayer(topBorder)
// Add bottom border to ListContainerView
let bottomBorder = CALayer()
bottomBorder.frame = CGRect(x: 0.0, y: self.frame.size.height - thickness, width: self.frame.size.width, height: thickness)
bottomBorder.backgroundColor = color
self.layer.addSublayer(bottomBorder)
}
}
As of now, the code properly adds a top border to the UIView. However, it is not adding the bottom border. I have tried numerous tactics from various StackOverflow answers but none have been successful. What am I doing incorrectly? How can I go about resolving this issue?
UPDATE: I have corrected the initial typo in my code. Additionally, here is a screenshot of an example of where this view is being accessed. In the screenshot, both of the Post View(s) are assigned the class ListContainerView.
Thank you in advance for any help you are able to provide!
Actually, I have the following UIView subclass similar to yours. Try it. It always works.
import UIKit
class TopBotView: UIView {
override func draw(_ rect: CGRect) {
let tHeight = self.frame.size.height
let topLayer = CALayer()
topLayer.frame = CGRect(x: 0.0, y: tHeight - 0.5, width: self.frame.size.width, height: 0.5)
topLayer.backgroundColor = UIColor.white.withAlphaComponent(0.3).cgColor
topLayer.masksToBounds = true
self.layer.addSublayer(topLayer)
let bottomLayer = CALayer()
bottomLayer.frame = CGRect(x: 0.0, y: 0.0, width: self.frame.size.width, height: 0.5)
bottomLayer.backgroundColor = UIColor.white.withAlphaComponent(0.3).cgColor
bottomLayer.masksToBounds = true
self.layer.addSublayer(bottomLayer)
}
}
UPDATE
If you want to surround all sides with a thin line, I have the following subclass.
import UIKit
class AllAroundView: UIView {
override func draw(_ rect: CGRect) {
let tHeight = self.frame.size.height
let topLayer = CALayer()
topLayer.frame = CGRect(x: 0.0, y: tHeight - 0.5, width: self.frame.size.width, height: 0.5)
topLayer.backgroundColor = UIColor.black.cgColor
topLayer.masksToBounds = true
self.layer.addSublayer(topLayer)
let bottomLayer = CALayer()
bottomLayer.frame = CGRect(x: 0.0, y: 0.0, width: self.frame.size.width, height: 0.5)
bottomLayer.backgroundColor = UIColor.black.cgColor
bottomLayer.masksToBounds = true
self.layer.addSublayer(bottomLayer)
let leftLayer = CALayer()
leftLayer.frame = CGRect(x: 0.0, y: 0.0, width: 0.5, height: self.frame.size.height)
leftLayer.backgroundColor = UIColor.black.cgColor
leftLayer.masksToBounds = true
self.layer.addSublayer(leftLayer)
let rightLayer = CALayer()
rightLayer.frame = CGRect(x: self.frame.size.width - 0.5, y: 0.0, width: 0.5, height: self.frame.size.height)
rightLayer.backgroundColor = UIColor.black.cgColor
rightLayer.masksToBounds = true
self.layer.addSublayer(rightLayer)
}
}
bottomBorder.frame = CGRect(x: 0.0, y: self.frame.size.width - thickness, width: self.frame.size.width, height: thickness)
shouldn't it be
bottomBorder.frame = CGRect(x: 0.0, y: self.frame.size.height - thickness, width: self.frame.size.width, height: thickness)
unless your UIView is a square

swift drawing borders around textview or labels

myLabel.layer.borderWidth = 0.5
myLabel.layer.borderColor = UIColor.green.cgColor
Thats a simple answer of drawing a border. However the issue is I need to draw the border only to the right and bottom. I also need another label to draw border on top and right. How can I draw border to specific sides, not all 4 sides?
Add a shape layer and draw the lines in that layer. Note that layers do not participate in auto layout so you need to put your code in viewDidLayoutSubviews or subclass uilabel and do this in layout subviews. Here is a playground example using the UILabel subclass:
import PlaygroundSupport
import UIKit
class L: UILabel {
var strokeColor = UIColor.blue
var strokeWidth = CGFloat(0.5)
private lazy var labelBorderLayer:CAShapeLayer = {
let shapeLayer = CAShapeLayer()
self.layer.addSublayer(shapeLayer)
return shapeLayer
}()
override func layoutSubviews() {
super.layoutSubviews()
let path = CGMutablePath()
path.move(to: CGPoint(x: 0, y: bounds.size.height))
path.addLine(to: CGPoint(x: bounds.size.width, y: bounds.size.height))
path.addLine(to: CGPoint(x: bounds.size.width, y: 0))
labelBorderLayer.path = path
labelBorderLayer.strokeColor = strokeColor.cgColor
labelBorderLayer.lineWidth = strokeWidth
labelBorderLayer.fillColor = UIColor.clear.cgColor
}
}
let v = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
let l = L(frame: v.frame.insetBy(dx: 50, dy: 80))
v.addSubview(l)
l.textColor = .white
l.textAlignment = .center
l.text = "gjgkjgjgjgj"
v.backgroundColor = .red
PlaygroundPage.current.liveView = v
Im not sure if you can do that with the actual label border. But but you can do something similar to this
public enum UIButtonBorderSide {
case Top, Bottom, Left, Right
}
extension UIButton {
public func addBorder(side: UIButtonBorderSide, color: UIColor, width: CGFloat) {
let border = CALayer()
border.backgroundColor = color.CGColor
switch side {
case .Top:
border.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: width)
case .Bottom:
border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: width)
case .Left:
border.frame = CGRect(x: 0, y: 0, width: width, height: self.frame.size.height)
case .Right:
border.frame = CGRect(x: self.frame.size.width - width, y: 0, width: width, height: self.frame.size.height)
}
self.layer.addSublayer(border)
}
}
Thats for UIButton, But you can probably adapt it easily.
Source: https://gist.github.com/Isuru-Nanayakkara/496d5713e61125bddcf5
Hope this helps