Cut transparent hole in the shape of UIImage into UIView - ios

I have an UIView in which I want to create a hole in the shape of the content of a UIImageView, but I can't get it to work. I can, however, mask an UIView to the shape of the UIImage.
My code:
let doorsMaskBounds = CGRect(x: 0, y: 0, width: 111, height: 111)
// Background view
let doorsBgView = UIView(frame: doorsMaskBounds)
doorsBgView.center = navigationController.view.center
doorsBgView.backgroundColor = UIColor.yellow
vc.view.addSubview(doorsBgView)
vc.view.bringSubview(toFront: doorsBgView)
// Logo Mask
doorsBgView.layer.mask = CALayer()
doorsBgView.layer.mask?.contents = UIImage(named: "doors")!.cgImage
doorsBgView.layer.mask?.bounds = doorsMaskBounds
doorsBgView.layer.mask?.anchorPoint = CGPoint(x: 0.5, y: 0.5)
doorsBgView.layer.mask?.position = CGPoint(x: doorsBgView.frame.width / 2, y: doorsBgView.frame.height / 2)
which results into:
I know how to "cut" a hole into a UIView in form of a shape I draw myself, as explained here, I just can't seem to figure out how the get the shape of the UIImage and apply it as the cut.

Related

Why the edges of UIView are not smooth for huge corner radius?

class AttributedView: UIView {
private let gradient = CAGradientLayer()
var cornerRadius: CGFloat = 3 {
didSet {
layer.cornerRadius = cornerRadius
}
}
}
I simply use it for both: button view (corner radius: 20) and background circle (corner radius: 600).
Why button is smooth, and background is not?
With iOS 13.0 you can simple do, in addition to setting corner radius
yourView.layer.cornerCurve = .continuous
You should use bezzier paths and draw circle. After that you will receive nice, smooth edges.
let context = UIGraphicsGetCurrentContext()!
let gradient = CGGradient(colorsSpace: nil, colors: [UIColor.red.cgColor, UIColor.white.cgColor] as CFArray, locations: [0, 1])!
let ovalPath = UIBezierPath(ovalIn: CGRect(x: 64, y: 9, width: 111, height: 93))
context.saveGState()
ovalPath.addClip()
context.drawLinearGradient(gradient, start: CGPoint(x: 119.5, y: 9), end: CGPoint(x: 119.5, y: 102), options: [])
context.restoreGState()
UIBezierPath is a simple and efficient class for drawing shapes using Swift, which you can then put into CAShapeLayer, SKShapeNode, or other places. It comes with various shapes built in, so you can write code like this to create a rounded rectangle or a circle:
let rect = CGRect(x: 0, y: 0, width: 256, height: 256)
let roundedRect = UIBezierPath(roundedRect: rect, cornerRadius: 50)
let circle = UIBezierPath(ovalIn: rect)
You can also create custom shapes by moving a pen to a starting position then adding lines:
let freeform = UIBezierPath()
freeform.move(to: .zero)
freeform.addLine(to: CGPoint(x: 50, y: 50))
freeform.addLine(to: CGPoint(x: 50, y: 150))
freeform.addLine(to: CGPoint(x: 150, y: 50))
freeform.addLine(to: .zero)
If your end result needs a CGPath, you can get one by accessing the cgPath property of your UIBezierPath.
You probably should clip bounds of this view:
attributedView.clipsToBounds = true

Add a complex boarder to UIImageView

How do I add boarder like in the below image (in Objective-C ) to UIImageView. I tried using UIBezierPath but wasn't successful.
Create a UIView (square in dimensions), add corner radius = 1/2 times its side.
Now add the UIImageView as a subview to this UIView.
As the image is circular in shape, so a simpler appraoch to the solution to your problem is to add corner radius to your UIVIew.
Below is the code I used:
let circleView: UIView = UIView(frame: CGRect(x: 0,
y: 0,
width: 100,
height: 100))
circleView.center = view.center
circleView.backgroundColor = .lightGray
circleView.layer.cornerRadius = 50
view.addSubview(circleView)
let imageView: UIImageView = UIImageView(frame: CGRect(x: 0,
y: 0,
width: 100,
height: 100))
imageView.image = UIImage(named: "F8FIs.png")
circleView.addSubview(imageView)
Please note that I added lightGray color to circle view for clarity.
And here is the screenshot of how it looks:

CAGradientLayer on UILabel can't be rotated

I want a horizontal color gradient as the text color of my UILabel.
So I'm using a CAGradientLayer as described in https://developer.apple.com/reference/quartzcore/cagradientlayer.
The gradient is rendered perfectly on the text, but vertically.
CATransform3DMakeRotation as apple described doesn't rotate the gradient.
In this answer it says that the CAGradientLayer needs to be added to a View or other Layer first to make the rotation work.
So I tried to add it as a sublayer to my UILabel and remove it after the rendering, but it won't transform the gradient on the text, but adds a horizontal gradient rectangle on top of it, in the size of the UILabel but rotated 90°.
Here's my code:
extension UILabel {
func addGradient() {
// Get size of the label
let size = CGSize(width: frame.width, height: frame.width)
let gradientLayer = CAGradientLayer()
gradientLayer.frame = CGRect(x: 0, y: 0, width: size.height, height: size.width)
gradientLayer.colors = [
UIColor.gradientBlue.cgColor,
UIColor.gradientPink.cgColor,
UIColor.gradientOrange.cgColor
]
// layer.addSublayer(gradientLayer)
gradientLayer.transform = CGAffineTransform
// This does not work
gradientLayer.transform = CATransform3DMakeRotation(CGFloat.pi / 2, 0, 0, 1)
UIGraphicsBeginImageContext(size)
gradientLayer.render(in: UIGraphicsGetCurrentContext()!)
// Create UIImage from Gradient
let gradientImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// gradientLayer.removeFromSuperlayer()
textColor = UIColor.init(patternImage: gradientImage!)
}
}
you can use
gradientLayer.startPoint = CGPoint.init(x: 0, y: 0)
gradientLayer.endPoint = CGPoint.init(x: 1, y: 1)
for diagonal gradient. you can play with those points however you want to achieve different results.

Playground code: AffineTransform and AnchorPoint don't work as I want

I want to shrink a triangle downward as below:
But the triangle shrink upward as below:
The transform code is below:
layer.setAffineTransform(CGAffineTransformMakeScale(1.0, 0.5))
I tried to use anchorPoint but I can't scceed.
//: Playground - noun: a place where people can play
import UIKit
let view = UIView(frame: CGRectMake(0, 0, 200, 150))
let layer = CAShapeLayer()
let triangle = UIBezierPath()
triangle.moveToPoint (CGPointMake( 50, 150))
triangle.addLineToPoint(CGPointMake(100, 50))
triangle.addLineToPoint(CGPointMake(150, 150))
triangle.closePath()
layer.path = triangle.CGPath
layer.strokeColor = UIColor.blueColor().CGColor
layer.lineWidth = 3.0
view.layer.addSublayer(layer)
view
layer.setAffineTransform(CGAffineTransformMakeScale(1.0, 0.5))
view
Anish gave me a advice but doesn't work well:
layer.setAffineTransform(CGAffineTransformMakeScale(2.0, 0.5))
Transforms operate around the layer's anchorPoint, which by default is at the center of the layer. Thus, you shrink by collapsing inwards, not by collapsing downwards.
If you want to shrink downward, you will need to scale down and change the view's position (or use a translate transform in addition to your scale transform), or change the layer's anchorPoint before performing the transform.
Another serious problem with your code is that your layer has no assigned size. This causes the results of your transform to be very misleading.
I ran this version of your code and got exactly the results you are asking for. I have put a star next to the key lines that I added. (Note that this is Swift 3; you really need to step up to the plate and update here.)
let view = UIView(frame:CGRect(x: 0, y: 0, width: 200, height: 150))
let layer = CAShapeLayer()
layer.frame = view.layer.bounds // *
let triangle = UIBezierPath()
triangle.move(to: CGPoint(x: 50, y: 150))
triangle.addLine(to: CGPoint(x: 100, y: 50))
triangle.addLine(to: CGPoint(x: 150, y: 150))
triangle.close()
layer.path = triangle.cgPath
layer.strokeColor = UIColor.blue.cgColor
layer.lineWidth = 3
view.layer.addSublayer(layer)
view
layer.anchorPoint = CGPoint(x: 0.5, y: 0) // *
layer.setAffineTransform(CGAffineTransform(scaleX: 1, y: 0.5))
view
Before:
After:

Using drawRect to draw & animate two graphs. A background graph, and a foreground graph

I am using drawRect to draw a pretty simple shape (dark blue in the image below).
I'd like this to animate from the left to the right, so that it grows. The caveat here is I need there to be a "max" background in gray, as seen in the top part of the image.
Right now, I'm simulating this animation by overlaying a white view, and then animating the size of it, so that it looks like the blue is animating to the right. While this works... I need the background gray shape to always be there. With my overlayed white view, this just doesn't work.
Here's the code for drawing the "current code" version:
let context = UIGraphicsGetCurrentContext()
CGContextMoveToPoint(context, 0, self.bounds.height - 6)
CGContextAddLineToPoint(context, self.bounds.width, 0)
CGContextAddLineToPoint(context, self.bounds.width, self.bounds.height)
CGContextAddLineToPoint(context, 0, self.bounds.height)
CGContextSetFillColorWithColor(context,UIColor(red: 37/255, green: 88/255, blue: 120/255, alpha: 1.0).CGColor)
CGContextDrawPath(context, CGPathDrawingMode.Fill)
How can I animate the blue part from left to right, while keeping the gray "max" portion of the graph always visible?
drawRect is producing still picture. To get animation you're saying about I'd recommend the following:
Use CoreAnimation to produce animation
Use UIBezierPath to make a shape you need
Use CALayer's mask to animate within required shape
Here is example code for Playground:
import UIKit
import QuartzCore
import XCPlayground
let view = UIView(frame: CGRect(x: 0, y: 0, width: 120, height: 40))
XCPlaygroundPage.currentPage.liveView = view
let maskPath = UIBezierPath()
maskPath.moveToPoint(CGPoint(x: 10, y: 30))
maskPath.addLineToPoint(CGPoint(x: 10, y: 25))
maskPath.addLineToPoint(CGPoint(x: 100, y: 10))
maskPath.addLineToPoint(CGPoint(x: 100, y: 30))
maskPath.closePath()
let maskLayer = CAShapeLayer()
maskLayer.path = maskPath.CGPath
maskLayer.fillColor = UIColor.whiteColor().CGColor
let rectToAnimateFrom = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 97, height: 40))
let rectToAnimateTo = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 0, height: 40))
let layerOne = CAShapeLayer()
layerOne.path = maskPath.CGPath
layerOne.fillColor = UIColor.grayColor().CGColor
let layerTwo = CAShapeLayer()
layerTwo.mask = maskLayer
layerTwo.fillColor = UIColor.greenColor().CGColor
view.layer.addSublayer(layerOne)
view.layer.addSublayer(layerTwo)
let animation = CABasicAnimation(keyPath: "path")
animation.fromValue = rectToAnimateFrom.CGPath
animation.toValue = rectToAnimateTo.CGPath
animation.duration = 1
animation.repeatCount = 1000
animation.autoreverses = true
layerTwo.addAnimation(animation, forKey: "Nice animation")
In your code, I only see you draw the graphic once, why not draw gray part first and then draw the blue part.
I don't think it is efficient enough to implement animation in drawRect function.
You can take a look at Facebook's Shimmer Example, it simulate the effect of iPhone unlock animation. It uses a mask layer. The idea could also work in your example.
Also, Facebook's pop framework could simplify your work.

Resources