How to apply an inverse text mask in Swift? - swift

I am trying programmatically create a layer with transparent text. Everything I try doesn't seem to work. My end goal is to create an inner shadow on text.
Instead of a circle as in the code below I want text.
let view = UIView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
view.backgroundColor = .white
// MASK
let blackSquare = UIView(frame: CGRect(x: 100, y: 100, width: 200, height: 200))
blackSquare.backgroundColor = .black
view.addSubview(blackSquare)
let maskLayer = CAShapeLayer()
// Create a path with the rectangle in it.
let path = CGMutablePath()
path.addArc(center: CGPoint(x: 100, y: 100), radius: 50, startAngle: 0.0, endAngle: 2.0 * .pi, clockwise: false)
path.addRect(CGRect(x: 0, y: 0, width: blackSquare.frame.width, height: blackSquare.frame.height))
maskLayer.backgroundColor = UIColor.black.cgColor
maskLayer.path = path;
maskLayer.fillRule = kCAFillRuleEvenOdd
blackSquare.layer.mask = maskLayer
maskLayer.masksToBounds = false
maskLayer.shadowRadius = 4
maskLayer.shadowOpacity = 0.5
maskLayer.shadowOffset = CGSize(width: 5, height: 5)
view.addSubview(blackSquare)
I'm also able to use text as a mask but I'm unable to invert the mask. Any help is appreciated.
EDIT:
I figured it out based on Rob's answer as suggested by Josh. Here's my playground code.
import Foundation
import UIKit
import PlaygroundSupport
// view
let view = UIView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
view.backgroundColor = .black
// button
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
button.setTitle("120", for: .normal)
button.setTitleColor(.white, for: .normal)
button.titleLabel?.font = UIFont(name: "AvenirNextCondensed-UltraLight", size: 200)
view.addSubview(button)
addInnerShadow(button: button)
func addInnerShadow(button: UIButton) {
// text
let text = button.titleLabel!.text!
// get context
UIGraphicsBeginImageContextWithOptions(button.bounds.size, true, 0)
let context = UIGraphicsGetCurrentContext()
context?.scaleBy(x: 1, y: -1)
context?.translateBy(x: 0, y: -button.bounds.size.height)
let font = button.titleLabel!.font!
// draw the text
let attributes = [
NSAttributedStringKey.font: font,
NSAttributedStringKey.foregroundColor: UIColor.white
]
let size = text.size(withAttributes: attributes)
let point = CGPoint(x: (button.bounds.size.width - size.width) / 2.0, y: (button.bounds.size.height - size.height) / 2.0)
text.draw(at: point, withAttributes: attributes)
// capture the image and end context
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// create image mask
let cgimage = image?.cgImage!
let bytesPerRow = cgimage?.bytesPerRow
let dataProvider = cgimage?.dataProvider!
let bitsPerPixel = cgimage?.bitsPerPixel
let width = cgimage?.width
let height = cgimage?.height
let bitsPerComponent = cgimage?.bitsPerComponent
let mask = CGImage(maskWidth: width!, height: height!, bitsPerComponent: bitsPerComponent!, bitsPerPixel: bitsPerPixel!, bytesPerRow: bytesPerRow!, provider: dataProvider!, decode: nil, shouldInterpolate: false)
// create background
UIGraphicsBeginImageContextWithOptions(button.bounds.size, false, 0)
UIGraphicsGetCurrentContext()!.clip(to: button.bounds, mask: mask!)
view.backgroundColor!.setFill()
UIBezierPath(rect: button.bounds).fill()
let background = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let backgroundView = UIImageView(image: background)
// add shadows
backgroundView.layer.shadowOffset = CGSize(width: 2, height: 2)
backgroundView.layer.shadowRadius = 2
backgroundView.layer.shadowOpacity = 0.75
button.addSubview(backgroundView)
}
PlaygroundPage.current.liveView = view

Whilst not exactly the same, please refer to the answer provided here by Rob who answered a similar question:
How do I style a button to have transparent text?
This should get you started at the very least...

Stumbled on a possible solution that I've updated to proper syntax:
func mask(withRect rect: CGRect, inverse: Bool = false) {
let path = UIBezierPath(rect: rect)
let maskLayer = CAShapeLayer()
if inverse {
path.append(UIBezierPath(rect: self.view.bounds))
maskLayer.fillRule = kCAFillRuleEvenOdd
}
maskLayer.path = path.cgPath
self.view.layer.mask = maskLayer
}
You'll obviously need to pick parts out to see if it works for you.

Related

Swift how to mask shape layer to blur layer

I was making a progress circle, and I want its track path to have a blur effect, is there any way to achieve that?
This is what the original track looks like(the track path is transparent, I want it to be blurred)
And this is my attempt
let outPutViewFrame = CGRect(x: 0, y: 0, width: 500, height: 500)
let circleRadius: CGFloat = 60
let circleViewCenter = CGPoint(x: outPutViewFrame.width / 2 , y: outPutViewFrame.height / 2)
let circleView = UIView()
let progressWidth: CGFloat = 8
circleView.frame.size = CGSize(width: (circleRadius + progressWidth) * 2, height: (circleRadius + progressWidth) * 2)
circleView.center = circleViewCenter
let circleTrackPath = UIBezierPath(arcCenter: CGPoint(x: circleView.frame.width / 2, y: circleView.frame.height / 2), radius: circleRadius, startAngle: -CGFloat.pi / 2, endAngle: 2 * CGFloat.pi, clockwise: true)
let blur = UIBlurEffect(style: .light)
let blurEffect = UIVisualEffectView(effect: blur)
blurEffect.frame = circleView.bounds
blurEffect.mask(withPath: circleTrackPath, inverse: false)
extension UIView {
func mask(withPath path: UIBezierPath, inverse: Bool = false) {
let maskLayer = CAShapeLayer()
if inverse {
path.append(UIBezierPath(rect: self.bounds))
maskLayer.fillRule = CAShapeLayerFillRule.evenOdd
}
maskLayer.path = path.cgPath
maskLayer.lineWidth = 5
maskLayer.lineCap = CAShapeLayerLineCap.round
self.layer.mask = maskLayer
}
}
Set maskLayer.fillRule to evenOdd, even when not inversed.
if inverse {
path.append(UIBezierPath(rect: self.bounds))
}
maskLayer.fillRule = CAShapeLayerFillRule.evenOdd
create the circleTrackPath by using a big circle and a smaller circle.
let circleCenter = CGPoint(x: circleView.frame.width / 2, y: circleView.frame.height / 2)
let circleTrackPath = UIBezierPath(ovalIn:
CGRect(origin: circleCenter, size: .zero)
.insetBy(dx: circleRadius, dy: circleRadius))
// smaller circle
circleTrackPath.append(CGRect(origin: circleCenter, size: .zero)
.insetBy(dx: circleRadius * 0.8, dy: circleRadius * 0.8))
Set circleTrackPath.usesEvenOddFillRule to true:
circleTrackPath.usesEvenOddFillRule = true
Now you have a blurred full circle. The non-blurred arc part can be implemented as another sublayer.
Here is a MCVE that you can paste into a playground:
let container = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
// change this to a view of your choice
let image = UIImageView(image: UIImage(named: "my_image"))
let blur = UIVisualEffectView(effect: UIBlurEffect(style: .light))
container.addSubview(image)
blur.frame = image.frame
container.addSubview(blur)
let outer = image.bounds.insetBy(dx: 30, dy: 30)
let path = UIBezierPath(ovalIn: outer)
path.usesEvenOddFillRule = true
path.append(UIBezierPath(ovalIn: outer.insetBy(dx: 10, dy: 10)))
let maskLayer = CAShapeLayer()
maskLayer.path = path.cgPath
maskLayer.fillRule = .evenOdd
blur.layer.mask = maskLayer
container // <--- playground quick look this
Using my profile pic as the background, this produces:

CAShapeLayer not rendering as desired

I have a view that's got some CAShapeLayers on it. I'm lazily instantiating it as follows:
lazy var myViewWithLayersOnIt: UIView = {
let view = UIView(frame: CGRect(origin: CGPoint(x: 14,
y: 2),
size: CGSize(width: 10,
height: 10)))
view.translatesAutoresizingMaskIntoConstraints = false
let outerCircleLayer = CAShapeLayer()
let outerPath = UIBezierPath(ovalIn: view.frame).cgPath
outerCircleLayer.path = outerPath
outerCircleLayer.position = view.center
outerCircleLayer.fillColor = UIColor.white.cgColor
view.layer.addSublayer(outerCircleLayer)
let innerFrame = CGRect(origin: CGPoint(x: 1.5,
y: 1.5),
size: CGSize(width: 8.5,
height: 8.5))
let innerCircleLayer = CAShapeLayer()
let innerPath = UIBezierPath(ovalIn: innerFrame).cgPath
innerCircleLayer.path = innerPath
innerCircleLayer.position = view.center
innerCircleLayer.fillColor = UIColor.red.cgColor
view.layer.addSublayer(innerCircleLayer)
return view
}()
While everything that's supposed to render on the screen is rendering, the CAShapeLayers aren't going in the center of the view. I thought it might be due to lazily instantiating, so I ditched lazy and I see the exact same issue. What did I forget to do?
This is how it's rendering:
Thank you for reading. I welcome your input.
You should use view.bounds instead of view.frame for outerPath. No need to set the position of outerCircleLayer, nor innerCircleLayer.
lazy var myViewWithLayersOnIt: UIView = {
let view = UIView(frame: CGRect(origin: CGPoint(x: 14,
y: 2),
size: CGSize(width: 10,
height: 10)))
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = UIColor.black
let outerCircleLayer = CAShapeLayer()
let outerPath = UIBezierPath(ovalIn: view.bounds).cgPath /// bounds!
outerCircleLayer.path = outerPath
// outerCircleLayer.position = view.center
outerCircleLayer.fillColor = UIColor.white.cgColor
view.layer.addSublayer(outerCircleLayer)
let innerFrame = CGRect(origin: CGPoint(x: 1.5,
y: 1.5),
size: CGSize(width: 8.5,
height: 8.5))
let innerCircleLayer = CAShapeLayer()
let innerPath = UIBezierPath(ovalIn: innerFrame).cgPath
innerCircleLayer.path = innerPath
// innerCircleLayer.position = view.center
innerCircleLayer.fillColor = UIColor.red.cgColor
view.layer.addSublayer(innerCircleLayer)
return view
}()
Result:
The red circle is off center because
let innerFrame = CGRect(origin: CGPoint(x: 1.5,
y: 1.5),
size: CGSize(width: 8.5,
height: 8.5))
should be
let innerFrame = CGRect(origin: CGPoint(x: 0.75,
y: 0.75),
size: CGSize(width: 8.5,
height: 8.5))
8.5 + 0.75 + 0.75 = 10, not 8.5 + 1.5 + 1.5 = 11.5

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()
}
}

Cant set right frame for ImageView

I cant set my UIImageView as half size of my tableview.backgroundview in upper part of my controller.
i tried to set origin of avatar as origin view, but it doesnt work.
let avatar = UIImageView(frame: self.view.frame)
let imgageOfAvatar = UIImage(named: "avatar.jpg")
avatar.image = imgageOfAvatar
avatar.frame = CGRect(x: self.view.frame.origin, y: self.view.frame.origin , width: self.view.frame.width, height: self.view.frame.height / 2)
avatar.frame.origin = self.view.frame.origin
//avatar.contentMode = UIViewContentMode.scaleAspectFill
self.tableView.addSubview(avatar)
self.tableView.sendSubview(toBack: avatar)
https://pp.userapi.com/c847120/v847120175/19f9cf/128kU2yWq-E.jpg
Try this
avatar.frame.origin.x = self.view.frame.origin.x
avatar.frame.origin.y = self.view.frame.origin.y
avatar.frame = CGRect(origin:self.view.frame.origin, size: width: self.view.frame.width, height: self.view.frame.height / 2)
you should add it to view like this:
let avatar = UIImageView(frame: self.view.frame)
let imgageOfAvatar = UIImage(named: "avatar.jpg")
avatar.image = imgageOfAvatar
avatar.frame = CGRect(x: self.view.frame.origin.x, y: self.view.frame.origin.y , width: self.view.frame.width, height: self.view.frame.height / 2)
avatar.frame.origin = self.view.frame.origin
self.view.insertSubview(avatar, at: 0)
I got the intended result
output
let avatar = UIImageView(frame: self.view.frame)
let imgageOfAvatar = UIImage(named: "dog.jpeg")
avatar.image = imgageOfAvatar
avatar.frame = CGRect(origin: self.view.frame.origin,
size: CGSize(width: self.view.frame.width,
height: self.view.frame.height / 2))
self.tableview.addSubview(avatar)
self.tableview.sendSubviewToBack(avatar)

Circular crop for photos from photo library when using UIImagePickerController

I am trying to change the square crop tool to circular one for the images selected from Photo Library in Swift 4. I tried many old codes available in here with no luck. Can somebody please help me.
There are mainly 2 issues in this code.
It doesn't hide the already existing square cropping area.
It shows the choose and cancel buttons under the old overlay, so cant tap on it.
Any help would be appreciated.
My code:
private func hideDefaultEditOverlay(view: UIView)
{
for subview in view.subviews
{
if let cropOverlay = NSClassFromString("PLCropOverlayCropView")
{
if subview.isKind(of: cropOverlay) {
subview.isHidden = true
break
}
else {
hideDefaultEditOverlay(view: subview)
}
}
}
}
private func addCircleOverlayToImageViewer(viewController: UIViewController) {
let circleColor = UIColor.clear
let maskColor = UIColor.black.withAlphaComponent(0.8)
let screenHeight = UIScreen.main.bounds.size.height
let screenWidth = UIScreen.main.bounds.size.width
hideDefaultEditOverlay(view: viewController.view)
let circleLayer = CAShapeLayer()
let circlePath = UIBezierPath(ovalIn: CGRect(x: 0, y: screenHeight - screenWidth, width: screenWidth, height: screenWidth))
circlePath.usesEvenOddFillRule = true
circleLayer.path = circlePath.cgPath
circleLayer.fillColor = circleColor.cgColor
let maskPath = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight), cornerRadius: 0)
maskPath.append(circlePath)
maskPath.usesEvenOddFillRule = true
let maskLayer = CAShapeLayer()
maskLayer.path = maskPath.cgPath
maskLayer.fillRule = kCAFillRuleEvenOdd
maskLayer.fillColor = maskColor.cgColor
viewController.view.layer.addSublayer(maskLayer)
// Move and Scale label
let label = UILabel(frame: CGRect(x: 0, y: 20, width: view.frame.width, height: 50))
label.text = "Move and Scale"
label.textAlignment = .center
label.textColor = UIColor.white
viewController.view.addSubview(label)
}