Custom frame UIView [duplicate] - ios

I want to achieve this result
So I need to add mask at bottom but Here What I got
Code I have tried
private func setupImageCutPath () {
let path = UIBezierPath()
path.move(to: .zero)
path.addLine(to: CGPoint(x: 0 , y: self.imgView.frame.height))
path.addLine(to: CGPoint(x: self.imgView.frame.width , y: self.imgView.frame.height - imageCutAwayPart))
path.addLine(to: CGPoint(x: self.imgView.frame.width, y: 0))
// Multiple tried to check from where masking is comming
self.maskLayer.fillColor = UIColor.gray.cgColor
self.maskLayer.lineWidth = 1.0
self.maskLayer.borderColor = UIColor.gray.cgColor
self.maskLayer.borderWidth = 1.0
self.maskLayer.path = path.cgPath
self.imgView.layer.mask = self.maskLayer
}
After scroll First time I am getting correct result
I don't understand What I am missing Any Help ?

I solved issue with
path.move(to: .zero)
/* THIS HELPLS ME */ path.addLine(to: CGPoint(x: 0 , y: self.imgView.frame.height - imageCutAwayPart / 2 ))
path.addLine(to: CGPoint(x: self.imgView.frame.width , y: self.imgView.frame.height - imageCutAwayPart))
path.addLine(to: CGPoint(x: self.imgView.frame.width, y: 0))
But I don't understand why I need to move CGPoint(x: 0 , y: self.imgView.frame.height - imageCutAwayPart / 2 ) instead of this CGPoint(x: 0 , y: self.imgView.frame.height)
If any one know this please post as answer I will surely accept the answer
EDIT
There was silly but smart mistake in Storybaord
Mistake was there is UIView which contains Label shown in screenshot. The Part visible is is the UIView I thought it masking is not working properly. Still there is issue that very first time in pageview controller mask is not proper but after scroll one time it is perfect.
EDIT2 Thanks to #DonMag
Following is working solution for every case
class CutOfImageView:UIImageView {
let imageCutAwayPart:CGFloat = 80
let maskLayer = CAShapeLayer()
override func layoutSubviews() {
super.layoutSubviews()
self.setupImageCutPath()
self.layer.mask = self.maskLayer
}
private func setupImageCutPath () {
let path = UIBezierPath()
path.move(to: .zero)
path.addLine(to: CGPoint(x: 0 , y: self.frame.height ))
path.addLine(to: CGPoint(x: self.frame.width , y: self.frame.height - imageCutAwayPart))
path.addLine(to: CGPoint(x: self.frame.width, y: 0))
path.close()
self.maskLayer.path = path.cgPath
}
}

Related

CAShapeLayer animation issue

I have a CAShapeLayer (below) which is used to draw a bubble. Which all works fine, as per designs but when i start resizing it within a tableView with tableView.beginUpdates() and tableView.endUpdates(). I end up having the old layer in black momentarily. which is looks awful. I am really puzzled on how to solve this. It kinda feels that layers are black, and the fill paints over them like a mask.
I have tried several things as to add/removing the layer in different places. etc. but result is always this.
video to describe it
override func draw(_ rect: CGRect) {
self.layer.backgroundColor = UIColor.clear.cgColor
let fillColor: UIColor = self.shapeColor
let shapeLayer = CAShapeLayer()
shapeLayer.contentsScale = UIScreen.main.scale
let path = UIBezierPath()
shapeLayer.fillColor = fillColor.cgColor
let width = self.bounds.size.width
let height = self.bounds.size.height
path.move(to: CGPoint(x: 3.02, y: height * 0.5))
path.move(to: CGPoint(x: 3.02, y: 24.9))
path.addLine(to: CGPoint(x: 3.02, y: 14.62))
path.addLine(to: CGPoint(x: 3.02, y: 14.62))
path.addCurve(to: CGPoint(x: 17.64, y: -0), controlPoint1: CGPoint(x: 3.02, y: 6.55),controlPoint2: CGPoint(x: 9.57, y: -0))
path.addLine(to: CGPoint(x: width - 15.85, y: 0))
path.addLine(to: CGPoint(x: width - 15.85, y: 0))
path.addCurve(to: CGPoint(x: width, y: 14.62), controlPoint1: CGPoint(x: width - 7.77, y: 0), controlPoint2: CGPoint(x: width, y: 6.55))
path.addLine(to: CGPoint(x: width, y: height - 15.1))
path.addLine(to: CGPoint(x: width, y: height - 15.1))
path.addCurve(to: CGPoint(x: width - 15.85, y: height), controlPoint1: CGPoint(x: width, y: height - 7.03), controlPoint2: CGPoint(x: width - 7.77, y: height))
path.addLine(to: CGPoint(x: 17.64, y: height))
path.addLine(to: CGPoint(x: 17.64, y: height))
path.addCurve(to: CGPoint(x: 8.69, y: height - 3.56), controlPoint1: CGPoint(x: 14.39, y: height),controlPoint2: CGPoint(x: 11.24, y: height - 1.57))
path.addLine(to: CGPoint(x: 8.79, y: height - 3.46))
path.addCurve(to: CGPoint(x: 0, y: height), controlPoint1: CGPoint(x: 7.27, y: height - 1.27), controlPoint2: CGPoint(x: 3.84, y: height + 0.51))
path.addCurve(to: CGPoint(x: 3.02, y: height - 14.1), controlPoint1: CGPoint(x: 4.06, y: height - 4.22), controlPoint2: CGPoint(x: 3.02, y: height - 9.62))
path.close()
if self.reverted {
let mirrorOverXOrigin: CGAffineTransform = CGAffineTransform(scaleX: -1.0, y: 1.0);
let translate: CGAffineTransform = CGAffineTransform(translationX: width, y: 0);
// Apply these transforms to the path
path.apply(mirrorOverXOrigin)
path.apply(translate)
}
path.fill()
shapeLayer.path = path.cgPath
shapeLayer.rasterizationScale = UIScreen.main.scale
shapeLayer.shouldRasterize = true
if let bubbleLayer = self.bubbleLayer {
self.layer.replaceSublayer(bubbleLayer, with: shapeLayer)
} else {
self.layer.insertSublayer(shapeLayer, at: 0)
}
self.bubbleLayer = shapeLayer
}
shapeLayer.path = path.cgPath
shapeLayer.rasterizationScale = UIScreen.main.scale
shapeLayer.shouldRasterize = true
self.layer.insertSublayer(shapeLayer, at: 0)
self.bubbleLayer?.removeFromSuperlayer()
self.bubbleLayer = shapeLayer
}
your solution cannot work. Draw(_ :) is not called during animation block. It is draw after tableView.endUpdates(), after UITableView ends animation.
Draw(_ :) - I don't think you should use it for your needs at all.
If I can recommend you some solution:
1) In awakeFromNib:
override func awakeFromNib() {
super.awakeFromNib()
self.contentView.backgroundColor = self.shapeColor
self.contentView.layer.cornerRadius = 15
/** make left view and attach it to the left bottom anchors with fixed size and draw into this view the shape of your left arrow***/
self.leftArrowView.isHidden = self.isReverted
/** make right view and attach it to the right bottom anchors with fixed size and draw into this view the shape of your right arrow***/
self.rightArrowView.isHidden = !self.isReverted
}
2) In prepareForReuse:
override func prepareForReuse() {
super.prepareForReuse()
self.leftArrowView.isHidden = self.isReverted
self.rightArrowView.isHidden = !self.isReverted
}
And this should cause your cell will change size smoothly.

How to add a custom shape to an UIImageView in Swift?

I'm trying to add a custom shape to an imageView. Please check the below images.
This is the required one:
This is what I have done so far:
I'm new to Core Graphics and I have done this so far:
private func customImageClipper(imageV: UIImageView){
let path = UIBezierPath()
let size = imageV.frame.size
print(size)
path.move(to: CGPoint(x: 0.0, y: size.height))
path.addLine(to: CGPoint(x: 0.8, y: size.height/2))
path.close()
let shape = CAShapeLayer()
shape.path = path.cgPath
imageV.layer.sublayers = [shape]
}
I'm creating a function to achieve a shape like this, but whenever I pass the imageView into this function, I can not see any change at all. I know that I have to move from points to another point to achieve this shape, but I have never done this. Any help would be appreciated. This is how I'm calling this function:
imageV.layoutIfNeeded()
customImageClipper(imageV: imageV)
P.S.: I'm not using Storyboard, I have created this programmatically.
There are many ways to create shapes using UIBezierPaths. This post here discusses the use of the draw function to create a shape.
Here is an example using your clip function within the cell.
func clip(imageView: UIView, withOffset offset: CGFloat) {
let path = UIBezierPath()
//Move to Top Left
path.move(to: .init(x: imageView.bounds.size.width * offset, y: 0))
//Draw line from Top Left to Top Right
path.addLine(to: .init(x: imageView.bounds.size.width, y: 0))
//Draw Line from Top Right to Bottom Right
path.addLine(to: .init(x: imageView.bounds.size.width * (1 - offset), y: imageView.bounds.size.height))
//Draw Line from Bottom Right to Bottom Left
path.addLine(to: .init(x: 0, y: imageView.bounds.size.height))
//Close Path
path.close()
//Create the Shape Mask for the ImageView
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.fillColor = UIColor.black.cgColor
imageView.layer.mask = shapeLayer
}
In this function, the offset is the amount of angle you would like on the shape, ranging from 0 to 1. (0.4) seems to work for your requirements.
This shares a lot of similarities with Apseri's answer, except I chose the route of percentages, rather than exact size. Nothing wrong with either approach, I just found it easier to understand with percentages. :)
One last note to point out, I used this function in the layoutSubviews function.
override func layoutSubviews() {
super.layoutSubviews()
imageView.layoutIfNeeded()
clip(imageView: self.imageView, withOffset: 0.4)
}
This output the following image:
Hope this helps.
Here is example of some path clipping. Of course path can be also put via parameters, and this can be applied to any view, as shown.
Before:
After (grey background is below ScrollView background):
func customImageClipper(imageV: UIView){
let path = UIBezierPath()
let size = imageV.frame.size
path.move(to: CGPoint(x: size.width/3.0, y: 0))
path.addLine(to: CGPoint(x: size.width/3.0 + 50, y: 0))
path.addLine(to: CGPoint(x: size.width/3.0, y: size.height))
path.addLine(to: CGPoint(x: size.width/3.0 - 50, y: size.height))
path.addLine(to: CGPoint(x: size.width/3.0, y: 0))
path.close()
let shape = CAShapeLayer()
shape.path = path.cgPath
shape.fillColor = UIColor.black.cgColor
imageV.layer.mask = shape
}
1- Subclassing your UIImageView
2- implement your custom drawings inside setNeedsLayout using UIBezierPath
class MyCustomImageView: UIImageView {
override func setNeedsLayout() {
let path = UIBezierPath()
path.moveToPoint(CGPoint(x: self.frame.size.width/2, y: self.frame.size.height))
path.addLineToPoint(CGPoint(x: self.frame.size.width, y: self.frame.size.height/2))
path.addLineToPoint(CGPoint(x: self.frame.size.width/2, y: 0))
path.addArcWithCenter(CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2), radius: self.frame.size.width/2, startAngle:-CGFloat(M_PI_2), endAngle: CGFloat(M_PI_2), clockwise: false)
path.moveToPoint(CGPoint(x: self.frame.size.width/2, y: self.frame.size.height))
path.closePath()
UIColor.redColor().setFill()
path.stroke()
path.bezierPathByReversingPath()
let shapeLayer = CAShapeLayer()
shapeLayer.frame = self.bounds
shapeLayer.path = path.CGPath
shapeLayer.fillColor = UIColor.redColor().CGColor
self.layer.mask = shapeLayer;
self.layer.masksToBounds = true;
}
}

UIImageView Mask Layer not coming from corners Until Scroll PageViewController First time

I want to achieve this result
So I need to add mask at bottom but Here What I got
Code I have tried
private func setupImageCutPath () {
let path = UIBezierPath()
path.move(to: .zero)
path.addLine(to: CGPoint(x: 0 , y: self.imgView.frame.height))
path.addLine(to: CGPoint(x: self.imgView.frame.width , y: self.imgView.frame.height - imageCutAwayPart))
path.addLine(to: CGPoint(x: self.imgView.frame.width, y: 0))
// Multiple tried to check from where masking is comming
self.maskLayer.fillColor = UIColor.gray.cgColor
self.maskLayer.lineWidth = 1.0
self.maskLayer.borderColor = UIColor.gray.cgColor
self.maskLayer.borderWidth = 1.0
self.maskLayer.path = path.cgPath
self.imgView.layer.mask = self.maskLayer
}
After scroll First time I am getting correct result
I don't understand What I am missing Any Help ?
I solved issue with
path.move(to: .zero)
/* THIS HELPLS ME */ path.addLine(to: CGPoint(x: 0 , y: self.imgView.frame.height - imageCutAwayPart / 2 ))
path.addLine(to: CGPoint(x: self.imgView.frame.width , y: self.imgView.frame.height - imageCutAwayPart))
path.addLine(to: CGPoint(x: self.imgView.frame.width, y: 0))
But I don't understand why I need to move CGPoint(x: 0 , y: self.imgView.frame.height - imageCutAwayPart / 2 ) instead of this CGPoint(x: 0 , y: self.imgView.frame.height)
If any one know this please post as answer I will surely accept the answer
EDIT
There was silly but smart mistake in Storybaord
Mistake was there is UIView which contains Label shown in screenshot. The Part visible is is the UIView I thought it masking is not working properly. Still there is issue that very first time in pageview controller mask is not proper but after scroll one time it is perfect.
EDIT2 Thanks to #DonMag
Following is working solution for every case
class CutOfImageView:UIImageView {
let imageCutAwayPart:CGFloat = 80
let maskLayer = CAShapeLayer()
override func layoutSubviews() {
super.layoutSubviews()
self.setupImageCutPath()
self.layer.mask = self.maskLayer
}
private func setupImageCutPath () {
let path = UIBezierPath()
path.move(to: .zero)
path.addLine(to: CGPoint(x: 0 , y: self.frame.height ))
path.addLine(to: CGPoint(x: self.frame.width , y: self.frame.height - imageCutAwayPart))
path.addLine(to: CGPoint(x: self.frame.width, y: 0))
path.close()
self.maskLayer.path = path.cgPath
}
}

How to clip a UIView with a bezier path?

I'm not totally sure to understand how UIBezierPath is supposed to work.
I have added a simple UIView in the middle of the screen, and I wanted to clip it by adding a mask to its layer. I tried this, thinking I'd get something like a losange in the middle of the view:
override func viewDidLoad() {
super.viewDidLoad()
viewToClip.backgroundColor = .white
let bezierPath = UIBezierPath()
bezierPath.move(to: viewToClip.center)
bezierPath.addLine(to: CGPoint(x: viewToClip.center.x - 5, y: viewToClip.center.y))
bezierPath.addLine(to: CGPoint(x: viewToClip.center.x, y: viewToClip.center.y - 5))
bezierPath.addLine(to: CGPoint(x: viewToClip.center.x + 5, y: viewToClip.center.y))
bezierPath.addLine(to: CGPoint(x: viewToClip.center.x, y: viewToClip.center.y + 5))
bezierPath.close()
let testLayer = CAShapeLayer()
testLayer.path = bezierPath.cgPath
viewToClip.layer.mask = testLayer
}
But instead of that, the view simply disappears from the screen. What am I doing wrong?
Thanks for your help.
Can you try
import UIKit
class bb: UIView {
var once:Bool = true
override func draw(_ rect: CGRect) {
if(once)
{
once = false
self.backgroundColor = .white
let bezierPath = UIBezierPath()
let cen = CGPoint.init(x: self.bounds.size.width/2, y: self.bounds.size.height/2)
bezierPath.move(to: cen)
bezierPath.addLine(to: CGPoint(x: cen.x - 5, y: cen.y))
bezierPath.addLine(to: CGPoint(x: cen.x, y: cen.y - 5))
bezierPath.addLine(to: CGPoint(x: cen.x + 5, y: cen.y))
bezierPath.addLine(to: CGPoint(x: cen.x, y: cen.y + 5))
bezierPath.close()
let testLayer = CAShapeLayer()
testLayer.path = bezierPath.cgPath
testLayer.lineWidth = 1.0
testLayer.strokeColor = UIColor.blue.cgColor
testLayer.fillColor = UIColor.green.cgColor
self.layer.addSublayer(testLayer)
}
}

Creating Triangle with UIBezierPath in Swift

I am trying to understand how to create a triangle shape with Swift. I found this code that creates a triangle.
class TriangleLayer: CAShapeLayer {
let innerPadding: CGFloat = 30.0
override init() {
super.init()
fillColor = Colors.red.CGColor
strokeColor = Colors.red.CGColor
lineWidth = 7.0
lineCap = kCALineCapRound
lineJoin = kCALineJoinRound
path = trianglePathSmall.CGPath
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var trianglePathSmall: UIBezierPath {
let trianglePath = UIBezierPath()
trianglePath.moveToPoint(CGPoint(x: 5.0 + innerPadding, y: 95.0)) // #1
trianglePath.addLineToPoint(CGPoint(x: 50.0, y: 12.5 + innerPadding)) // #2
trianglePath.addLineToPoint(CGPoint(x: 95.0 - innerPadding, y: 95.0)) // #3
trianglePath.closePath()
return trianglePath
}
And this code creates a shape like this
in the middle of the screen.
I tried to tweak and play around with it to understand how it works; however, at this point I realised that I got lost with the logic quite a bit. I placed the CGPoints of above triangle on an x-y axis in my head and it seems something like:
#1 x:35, y:95 #3 x:65, y:95
  #2 x:50, y: 42.5
But the triangle is created upside-down if I place the dots on the x-y axis.
What I want to achieve is what the axis tells, and I want to achieve..
. . .
<like this. not this>
. . .
You just have the axes in your head upside down. The coordinate system starts at 0,0 and extends right in X and down in Y.
So your points are really:
#2 x:50, y: 42.5
#1 x:35, y:95 #3 x:65, y:95
to get your desired triangle you'd have something like:
#1 x:35, y:95 #3 x:65, y:95
#2 x:50, y: 147.5
Result triangles
Code in swift5
//TriangleView
extension UIView {
func setRightTriangle(targetView:UIView?){
let heightWidth = targetView!.frame.size.width //you can use triangleView.frame.size.height
let path = CGMutablePath()
path.move(to: CGPoint(x: heightWidth/2, y: 0))
path.addLine(to: CGPoint(x:heightWidth, y: heightWidth/2))
path.addLine(to: CGPoint(x:heightWidth/2, y:heightWidth))
path.addLine(to: CGPoint(x:heightWidth/2, y:0))
let shape = CAShapeLayer()
shape.path = path
shape.fillColor = UIColor.blue.cgColor
targetView!.layer.insertSublayer(shape, at: 0)
}
func setLeftTriangle(targetView:UIView?){
let heightWidth = targetView!.frame.size.width
let path = CGMutablePath()
path.move(to: CGPoint(x: heightWidth/2, y: 0))
path.addLine(to: CGPoint(x:0, y: heightWidth/2))
path.addLine(to: CGPoint(x:heightWidth/2, y:heightWidth))
path.addLine(to: CGPoint(x:heightWidth/2, y:0))
let shape = CAShapeLayer()
shape.path = path
shape.fillColor = UIColor.blue.cgColor
targetView!.layer.insertSublayer(shape, at: 0)
}
func setUpTriangle(targetView:UIView?){
let heightWidth = targetView!.frame.size.width
let path = CGMutablePath()
path.move(to: CGPoint(x: 0, y: heightWidth))
path.addLine(to: CGPoint(x:heightWidth/2, y: heightWidth/2))
path.addLine(to: CGPoint(x:heightWidth, y:heightWidth))
path.addLine(to: CGPoint(x:0, y:heightWidth))
let shape = CAShapeLayer()
shape.path = path
shape.fillColor = UIColor.blue.cgColor
targetView!.layer.insertSublayer(shape, at: 0)
}
func setDownTriangle(targetView:UIView?){
let heightWidth = targetView!.frame.size.width
let path = CGMutablePath()
path.move(to: CGPoint(x: 0, y: 0))
path.addLine(to: CGPoint(x:heightWidth/2, y: heightWidth/2))
path.addLine(to: CGPoint(x:heightWidth, y:0))
path.addLine(to: CGPoint(x:0, y:0))
let shape = CAShapeLayer()
shape.path = path
shape.fillColor = UIColor.blue.cgColor
targetView!.layer.insertSublayer(shape, at: 0)
}
}
Swift 4.*
The easiest way of doing it by using AutoLayout:
Open your Storyboard and drag a UIView in UIViewController, position it and set the size as you wish (that's the place where the triangle will be). Set the view background to be transparent.
Create a new class, you can name it however you want (I named mine TriangleView). This will be the content of that class:
class TriangleView: UIView {
// predefined variables that can be changed
var startPoint: CGPoint = CGPoint(x: 0.0, y: 0.5)
var endPoint: CGPoint = CGPoint(x: 1.0, y: 0.5)
var firstGradientColor: UIColor = UIColor.white
var secondGradientColor: UIColor = UIColor.blue
let gradient: CAGradientLayer = CAGradientLayer()
override func draw(_ rect: CGRect) {
let height = self.layer.frame.size.height
let width = self.layer.frame.size.width
// draw the triangle
let path = UIBezierPath()
path.move(to: CGPoint(x: width / 2, y: 0))
path.addLine(to: CGPoint(x: width, y: height))
path.addLine(to: CGPoint(x: 0, y: height))
path.close()
// draw the triangle 'upside down'
// let path = UIBezierPath()
// path.move(to: CGPoint(x: 0, y: 0))
// path.addLine(to: CGPoint(x: width, y: 0))
// path.addLine(to: CGPoint(x: width / 2, y: height))
// path.close()
// add path to layer
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.lineWidth = 1.0
// Add the gradient for the view background if needed
gradient.colors = [firstGradientColor.cgColor, secondGradiendColor.cgColor]
gradient.startPoint = startPoint
gradient.endPoint = endPoint
gradient.frame = self.bounds
gradient.mask = shapeLayer
self.layer.addSublayer(gradient)
}
}
Go to your Storyboard, select the UIView and in Identity Inspector write the class name TriangleView
Enjoy your triangle! :)

Resources