Get PDF from a UILabel text mask - ios

I'm trying to get PDF from UIView with UILabel text mask.
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 200 ))
label.text = "Label Text"
label.font = UIFont.systemFont(ofSize: 25)
label.textAlignment = .center
label.textColor = UIColor.white
let overlayView = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200 ))
overlayView.image = UIImage(named: "erasemask.png")
label.mask = overlayView
view_process.addSubview(label)
}
func exportAsPdfFromView(){
let pdfPageFrame = CGRect(x: 0, y: 0, width: view_process.bounds.size.width, height: view_process.bounds.size.height)
let pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, pdfPageFrame, nil)
UIGraphicsBeginPDFPageWithInfo(pdfPageFrame, nil)
guard let pdfContext = UIGraphicsGetCurrentContext() else { return "" }
view_process.layer.render(in: pdfContext)
UIGraphicsEndPDFContext()
let path = self.saveViewPdf(data: pdfData)
print(path)
}
func saveViewPdf(data: NSMutableData) -> String {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let docDirectoryPath = paths[0]
let pdfPath = docDirectoryPath.appendingPathComponent("viewPdf.pdf")
if data.write(to: pdfPath, atomically: true) {
return pdfPath.path
} else {
return ""
}
}
but I do not get PDF with mask. I don't want to convert UIView to UImage and then convert UImage to PDF. I want to editable PDF so don't want to convert into UIImage.
Can anyone help me How to convert Masked UILabel to PDF ?
here erasemask.png

You have to draw text yourself in the pdf to make it editable.
I have slightly modified your code, and it works. You can simply copy/paste in a new app view controller to check the result.
Here is a screenshot of the document opened in AffinityDesigner. The mask is correctly applied as a layer mask, and the text is editable.
It needs some tweaking to respect exact layout.
import UIKit
class ViewController: UIViewController {
var labelFrame: CGRect { return CGRect(x: 0, y: 0, width: 200, height: 200 )}
lazy var label: UILabel = {
let label = UILabel(frame: labelFrame)
label.text = "Label Text"
label.font = UIFont.systemFont(ofSize: 25)
label.textAlignment = .center
label.textColor = UIColor.black
return label
}()
var maskImage = UIImage(named: "erasemask.png")
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(label)
let overlayView = UIImageView(frame: labelFrame)
overlayView.image = maskImage
label.mask = overlayView
exportAsPdfFromView()
}
func exportAsPdfFromView() {
let pdfPageFrame = CGRect(x: 0, y: 0, width: view.bounds.size.width, height: view.bounds.size.height)
let pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, pdfPageFrame, nil)
UIGraphicsBeginPDFPageWithInfo(pdfPageFrame, nil)
guard let context = UIGraphicsGetCurrentContext() else { return }
// Clip context
if let overlayImage = maskImage?.cgImage {
context.clip(to: labelFrame, mask: overlayImage)
}
// Draw String
let string: String = label.text ?? ""
let attributes: [NSAttributedString.Key: Any] = [
NSAttributedString.Key.foregroundColor: label.textColor ?? .black,
NSAttributedString.Key.font: label.font ?? UIFont.systemFont(ofSize: 25)
]
let stringRectSize = string.size(withAttributes: attributes)
let x = (labelFrame.width - stringRectSize.width) / 2
let y = (labelFrame.height - stringRectSize.height) / 2
let stringRect = CGRect(origin: CGPoint(x: x, y: y), size: stringRectSize)
string.draw(in: stringRect, withAttributes: attributes)
UIGraphicsEndPDFContext()
saveViewPdf(data: pdfData)
}
func saveViewPdf(data: NSMutableData) {
guard let docDirectoryPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let pdfPath = docDirectoryPath.appendingPathComponent("viewPdf.pdf")
print(pdfPath)
data.write(to: pdfPath, atomically: true)
}
}
EDITED
As a comparison, I have added the result by using the Apple view.render function, using code from the question ( with a blue background so we can see white text ). It clearly shows that this function does not support editable text and masking.
It exports the document as a stack of flat images and extra - useless - groups.
So I guess the only solution to keep pdf entities types is to compose the document by rendering each object.
If you need to export complex forms, it must not be too hard to make a helper that crawls in the view hierarchy and render each object content.
If you need to also render pdf with interactive buttons, you will probably need to use Annotations( available in PDFKit ). By the way you can also create editable fields with annotations, but I'm not sure it supports masking.
LAST EDIT:
Since you use an external framework to render pdf ( PDFGenerator ), it is different. You can only override the view.layer.render function that is used by the framework and use the context.clip function.
To export ui components as editable, I think they must have no superview. As soon as there is a view hierarchy, a backing bitmap is created, and all render calls are made with this bitmap as parameter, and not the PDFContext that was used to call the first render.
That's how PDFGenerator works, it crawls in the view hierarchy an render views by removing them from superview, render to the context, and move them back in hierarchy.
The big drawback of this is that it leads to bugs when the view is moved back in the hierarchy. Probably because constraints are lost, or some views like UIStackView behave differently. There is numerous opened issues around this on their github.
What I don't really understand yet is why the label below is rendered as editable even in a view hierarchy. I guess it's due to how the render function is done by Apple. Can't go further on this right now..
Custom Field Example:
It may need more work to respect exact field layout, but this is a basis for a view that is rendered as editable text. It gives the exact same result as in the first part of the answer.
It works with any mask view, not only UIImage.
It is rendered as editable even in a hierarchy.
So if you use this label instead of UILabel in the initial code of this question, it works.
// Extension to get mask view as an image
extension UIView {
var cgImage: CGImage? {
UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, contentScaleFactor);
guard let context = UIGraphicsGetCurrentContext() else { return nil }
layer.render(in: context)
let image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image?.cgImage
}
}
class PMLayer: CALayer {
// Needed to access text style
weak var label: UILabel?
override init() { super.init() }
required init?(coder: NSCoder) { super.init(coder: coder) }
override init(layer: Any) {
super.init(layer: layer)
if let pm = layer as? PMLayer {
label = pm.label
}
}
override func render(in ctx: CGContext) {
guard let label = label else { return }
// Clip context
if let mask = label.mask?.cgImage {
ctx.clip(to: label.frame, mask: mask)
}
// Draw String
let string: String = label.text ?? ""
let attributes: [NSAttributedString.Key: Any] = [
NSAttributedString.Key.foregroundColor: label.textColor ?? .black,
NSAttributedString.Key.font: label.font ?? UIFont.systemFont(ofSize: 25)
]
let stringRectSize = string.size(withAttributes: attributes)
let x = (label.frame.width - stringRectSize.width) / 2
let y = (label.frame.height - stringRectSize.height) / 2
let stringRect = CGRect(origin: CGPoint(x: x, y: y), size: stringRectSize)
string.draw(in: stringRect, withAttributes: attributes)
}
}
class PMLabel: UILabel {
override class var layerClass: AnyClass { return PMLayer.self }
// Be sure the label is correctly linked to the layer when we access it
override var layer: CALayer {
(super.layer as? PMLayer)?.label = self
return super.layer
}
}

this is my decision
import UIKit
import PDFKit
class ViewController: UIViewController {
#IBOutlet weak var view_process: UIView!
#IBOutlet weak var pdf_view: UIView!
let documentInteractionController = UIDocumentInteractionController()
#IBAction func bClick(_ sender: Any) {
exportAsPdfFromView()
}
override func viewDidLoad() {
super.viewDidLoad()
documentInteractionController.delegate = self
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 200 ))
label.text = "Label Text"
label.font = UIFont.systemFont(ofSize: 25)
label.textAlignment = .center
label.textColor = UIColor.blue
let overlayView = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200 ))
overlayView.image = UIImage(named: "erasemask.png")
label.mask = overlayView
view_process.addSubview(label)
}
func exportAsPdfFromView(){
let pdfPageFrame = view_process.bounds//.CGRect(x: 0, y: 0, width: view_process.bounds.size.width, height: view_process.bounds.size.height)
let pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, pdfPageFrame, nil)
UIGraphicsBeginPDFPageWithInfo(pdfPageFrame, nil)
let pdfContext = UIGraphicsGetCurrentContext()!
view_process.layer.render(in: pdfContext)
UIGraphicsEndPDFContext()
let path = self.saveViewPdf(data: pdfData)
print(path)
self.share(url: URL(string: "file://\(path)")!)
}
func saveViewPdf(data: NSMutableData) -> String {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let docDirectoryPath = paths[0]
let pdfPath = docDirectoryPath.appendingPathComponent("viewPdf.pdf")
if data.write(to: pdfPath, atomically: true) {
return pdfPath.path
} else {
return ""
}
}
func openPdf(path: String) {
let pdfView = PDFView(frame: self.view.bounds)
pdfView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
pdf_view.addSubview(pdfView)
// Fit content in PDFView.
pdfView.autoScales = true
// Load Sample.pdf file from app bundle.
let fileURL = URL(string: path)
pdfView.document = PDFDocument(url: fileURL!)
}
func share(url: URL) {
documentInteractionController.url = url
// documentInteractionController.uti = url.typeIdentifier ?? "public.data, public.content"
// documentInteractionController.name = url.localizedName ?? url.lastPathComponent
documentInteractionController.presentPreview(animated: true)
}
}
extension ViewController: UIDocumentInteractionControllerDelegate {
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
guard let navVC = self.navigationController else {
return self
}
return navVC
}
}

Related

Detect clicked mutable attributed string

I have this code to write a paragraph like book with numbering for each sentence , the problem I'm facing is i can't find how to color one sentence when the user clicks in any word from it
import UIKit
let descender: CGFloat = UIFont.systemFont(ofSize: 25).descender
class ViewController: UIViewController , UITextViewDelegate, UIGestureRecognizerDelegate {
var all = [NSMutableAttributedString]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let style = NSMutableParagraphStyle()
style.alignment = NSTextAlignment.justified
style.baseWritingDirection = .rightToLeft
style.lineBreakMode = .byWordWrapping
let myAttribute = [ NSAttributedString.Key.font: UIFont.systemFont(ofSize: 25)] // ,
// NSAttributedString.Key.paragraphStyle: style ,
// NSAttributedString.Key.baselineOffset: NSNumber(value: 0)]
let textView = UITextView(frame:CGRect(x: 20, y: 100, width: UIScreen.main.bounds.width - 40 , height: UIScreen.main.bounds.height))
let attributedString = NSMutableAttributedString()
Array(1..<50).forEach {
let small = $0 % 2 == 0 ? " long text part one long text part one long text part one long text part one long text part one long text part one long text part one long text part one long text part one " : "long text part two long text part twolong text part twolong text part twolong text part twolong text part twolong text part twolong text part two "
let attributedString2 = NSMutableAttributedString(string: small,attributes: myAttribute)
attributedString.append(attributedString2)
let textAttachment11 = SubTextAttachment()
textAttachment11.image = generateImageWithText(text: "\($0)")
let attrStringWithImage11 = NSAttributedString(attachment: textAttachment11)
attributedString.append(attrStringWithImage11)
}
textView.attributedText = attributedString;
self.view.addSubview(textView)
textView.isEditable = false
textView.isSelectable = true
textView.delegate = self
let tap = UITapGestureRecognizer(target: self, action: #selector(self.textTapped(_:)))
tap.delegate = self
textView.isUserInteractionEnabled = true
textView.addGestureRecognizer(tap)
}
func generateImageWithText(text: String) -> UIImage? {
let image = UIImage(named: "qqq")!
print(text," ",image.size)
let imageView = UIImageView(image: image)
imageView.backgroundColor = UIColor.clear
imageView.frame = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
let label = UILabel(frame: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
label.font = UIFont.systemFont(ofSize: 50)
label.backgroundColor = UIColor.clear
label.textAlignment = .center
label.textColor = UIColor.black
label.text = text
UIGraphicsBeginImageContextWithOptions(label.bounds.size, false, 0)
imageView.layer.render(in: UIGraphicsGetCurrentContext()!)
label.layer.render(in: UIGraphicsGetCurrentContext()!)
let imageWithText = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return imageWithText
}
#objc func textTapped(_ sender:UITapGestureRecognizer) {
}
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
return true
}
}
class SubTextAttachment:NSTextAttachment {
override func attachmentBounds(for textContainer: NSTextContainer?, proposedLineFragment lineFrag: CGRect, glyphPosition position: CGPoint, characterIndex charIndex: Int) -> CGRect {
let height = lineFrag.size.height
var scale: CGFloat = 1.0;
let imageSize = image!.size
if (height < imageSize.height) {
scale = height / imageSize.height
}
let value = CGRect(x: 0, y: descender, width: imageSize.width * scale, height: imageSize.height * scale)
return value
}
}
I know how to change the foreground color of any sub attributed string , but how i can know that the clicked part belong to the one to be colored ?
Also is there any better way to build this UI (in terms of performance ) as with tableView/CollectionView there is a dequeueing but here there isn't ?
So any hep is greatly appreciated
With NSAttributedString , you can use CoreText to render.
Convert NSAttributedString to CTFrame, then render it.
The key part
when you click a word in paragraph,
with override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
you can get a CGPoint
with that CGPoint & CTFrame, you can know the text range clicked in the text.
then rebuild the NSAttributedString 、CTFrame & rerender
here is the code you can refer
import UIKit
import CoreText
class TextRenderView: UIView {
let frameRef:CTFrame
let theSize: CGSize
let keyOne = //...
let keyTwo = //...
let rawTxt: String
let contentPage: NSAttributedString
let keyRanges: [Range<String.Index>]
override init(frame: CGRect){
rawTxt = //...
var tempRanges = [Range<String.Index>]()
if let rangeOne = rawTxt.range(of: keyOne){
tempRanges.append(rangeOne)
}
if let rangeTwo = rawTxt.range(of: keyTwo){
tempRanges.append(rangeTwo)
}
keyRanges = tempRanges
contentPage = NSAttributedString(string: rawTxt, attributes: [NSAttributedString.Key.font: UIFont.regular(ofSize: 15), NSAttributedString.Key.foregroundColor: UIColor.black])
let calculatedSize = contentPage.boundingRect(with: CGSize(width: UI.std.width - CGFloat(15 * 2), height: UI.std.height), options: [.usesFontLeading, .usesLineFragmentOrigin], context: nil).size
let padding: CGFloat = 10
theSize = CGSize(width: calculatedSize.width, height: calculatedSize.height + padding)
let framesetter = CTFramesetterCreateWithAttributedString(contentPage)
let path = CGPath(rect: CGRect(origin: CGPoint.zero, size: theSize), transform: nil)
frameRef = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, nil)
super.init(frame: frame)
backgroundColor = UIColor.white
}
required init?(coder: NSCoder) {
fatalError()
}
override func draw(_ rect: CGRect) {
guard let ctx = UIGraphicsGetCurrentContext() else{
return
}
ctx.textMatrix = CGAffineTransform.identity
ctx.translateBy(x: 0, y: bounds.size.height)
ctx.scaleBy(x: 1.0, y: -1.0)
CTFrameDraw(frameRef, ctx)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
guard let touch = touches.first else{
return
}
let pt = touch.location(in: self)
guard let offset = parserRect(with: pt, frame: frameRef), let pos = rawTxt.index(rawTxt.startIndex, offsetBy: offset, limitedBy: rawTxt.endIndex) else{
return
}
if keyRanges[0].contains(pos){
print(0)
}
else if keyRanges[1].contains(pos){
print(1)
}
}
func parserRect(with point: CGPoint, frame textFrame: CTFrame) -> Int?{
var result: Int? = nil
let path: CGPath = CTFrameGetPath(textFrame)
let bounds = path.boundingBox
guard let lines = CTFrameGetLines(textFrame) as? [CTLine] else{
return result
}
let lineCount = lines.count
guard lineCount > 0 else {
return result
}
var origins = [CGPoint](repeating: CGPoint.zero, count: lineCount)
CTFrameGetLineOrigins(frameRef, CFRangeMake(0, 0), &origins)
for i in 0..<lineCount{
let baselineOrigin = origins[i]
let line = lines[i]
var ascent: CGFloat = 0
var descent: CGFloat = 0
var linegap: CGFloat = 0
let lineWidth = CTLineGetTypographicBounds(line, &ascent, &descent, &linegap)
let lineFrame = CGRect(x: baselineOrigin.x, y: bounds.height-baselineOrigin.y-ascent, width: CGFloat(lineWidth), height: ascent+descent+linegap + 10)
if lineFrame.contains(point){
result = CTLineGetStringIndexForPosition(line, point)
break
}
}
return result
}
}
helper method:
extension String {
func range(ns inner: String) -> NSRange{
return (self as NSString).range(of: inner)
}
}
here is the github code you can refer

how to make save button to swift 5?

I'm creating a wallpaper app for iOS. I've created a UIImageView, but am stuck on saving the image. I have solved the permissions but am unable to have the user save the image. I created the save button itself, but I don't know to make save any image from the image array in the user's image gallery.
Here is my code so far:
class ViewController: UIViewController {
#IBOutlet var imageview: [UIScrollView]!
#IBOutlet weak var saveButton: UIButton!
#IBAction func saveButtonPressed(_ sender: UIButton) {
// TODO: - How to save the image here
}
let scrollView: UIScrollView = {
let scroll = UIScrollView()
scroll.isPagingEnabled = true
scroll.showsVerticalScrollIndicator = false
scroll.showsHorizontalScrollIndicator = false
scroll.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
return scroll
}()
var imageArray = [UIImage]()
func setupImages(_ images: [UIImage]){
for i in 0..<images.count {
let imageView = UIImageView()
imageView.image = images[i]
let xPosition = UIScreen.main.bounds.width * CGFloat(i)
imageView.frame = CGRect(x: xPosition, y: 0, width: scrollView.frame.width, height: scrollView.frame.height)
imageView.contentMode = .scaleAspectFit
scrollView.contentSize.width = scrollView.frame.width * CGFloat(i + 1)
scrollView.addSubview(imageView)
//scrollView.delegate = (self as! UIScrollViewDelegate)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.addSubview(scrollView)
imageArray = [#imageLiteral(resourceName: "1"),#imageLiteral(resourceName: "10"),#imageLiteral(resourceName: "9"),#imageLiteral(resourceName: "8"),#imageLiteral(resourceName: "3")]
setupImages(imageArray)
}
}
You will need to add a saveImage function:
func saveImage(image: UIImage) -> Bool {
guard let data = UIImageJPEGRepresentation(image, 1) ?? UIImagePNGRepresentation(image) else {
return false
}
guard let directory = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) as NSURL else {
return false
}
do {
try data.write(to: directory.appendingPathComponent("fileName.png")!)
return true
} catch {
print(error.localizedDescription)
return false
}
}
And then in saveButtonPressed:
let success = saveImage(image: imageArray[0])
print("Did \(success ? "" : "not ")store image successfully")
You'll need to add some logic to actually select the image.

Transform UIView to UIImage and set it with UIImageView

I refered to this question, and did add extension to UIView:
extension UIView {
// Using a function since `var image` might conflict with an existing variable
// (like on `UIImageView`)
func asImage() -> UIImage {
if #available(iOS 10.0, *) {
let renderer = UIGraphicsImageRenderer(bounds: bounds)
return renderer.image { rendererContext in
layer.render(in: rendererContext.cgContext)
}
} else {
UIGraphicsBeginImageContext(self.frame.size)
self.layer.render(in:UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return UIImage(cgImage: image!.cgImage!)
}
}
}
Then i create very simple test view:
private class FakeTestView: BaseView {
override func prepare() {
backgroundColor = .blue
setup()
}
private func setup(){
let lbl = LabelSL.regular()
lbl.text = "LabelSL.regular()"
addSubview(lbl)
lbl.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
lbl.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
}
}
That view showing correctly when treated as UIView.
Finally, i tried:
let newSlideFrame = CGRect(x: CGFloat(i) * event.expectedWidth(),
y: 0,
width: event.expectedWidth(),
height: frame.size.height)
let imgView = UIImageView()
imgView.contentMode = .scaleAspectFit
imgView.frame = newSlideFrame
imgView.image = FakeTestView().asImage()
scroll.addSubview(imgView)
But there is nothing showing. Code from above work when i try to add UIView, or UIImageView with sample images.

how to make exact blur

I want Blur actual like first Image.
I have did some code and made it like second image.
My Code For Blur is Like
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.layer.opacity = 0.8
blurEffectView.alpha = 0.6
blurEffectView.frame = CGRectMake(0, 42, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height - 42)
sourceView.addSubview(blurEffectView)
Sourceview is my background view. Which I wants to make blur. Any Suggestion ?
The alpha and the layer.opacity corrections are not necessary, you can do it also with an extension:
extension UIImageView{
func makeBlurImage(imageView:UIImageView?)
{
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = imageView!.bounds
blurEffectView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] // to support device rotation
imageView?.addSubview(blurEffectView)
}
}
Usage:
let imageView = UIImageView(frame: CGRectMake(0, 100, 300, 400))
let image:UIImage = UIImage(named: "photo.png")!
imageView.image = image
//Apply blur effect
imageView.makeBlurImage(imageView)
self.view.addSubview(imageView)
But if you want to apply the blur effect to an UIView you can use this code:
protocol Blurable
{
var layer: CALayer { get }
var subviews: [UIView] { get }
var frame: CGRect { get }
var superview: UIView? { get }
func addSubview(view: UIView)
func removeFromSuperview()
func blur(blurRadius blurRadius: CGFloat)
func unBlur()
var isBlurred: Bool { get }
}
extension Blurable
{
func blur(blurRadius blurRadius: CGFloat)
{
if self.superview == nil
{
return
}
UIGraphicsBeginImageContextWithOptions(CGSize(width: frame.width, height: frame.height), false, 1)
layer.renderInContext(UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
guard let blur = CIFilter(name: "CIGaussianBlur"),
this = self as? UIView else
{
return
}
blur.setValue(CIImage(image: image), forKey: kCIInputImageKey)
blur.setValue(blurRadius, forKey: kCIInputRadiusKey)
let ciContext = CIContext(options: nil)
let result = blur.valueForKey(kCIOutputImageKey) as! CIImage!
let boundingRect = CGRect(x:0,
y: 0,
width: frame.width,
height: frame.height)
let cgImage = ciContext.createCGImage(result, fromRect: boundingRect)
let filteredImage = UIImage(CGImage: cgImage)
let blurOverlay = BlurOverlay()
blurOverlay.frame = boundingRect
blurOverlay.image = filteredImage
blurOverlay.contentMode = UIViewContentMode.Left
if let superview = superview as? UIStackView,
index = (superview as UIStackView).arrangedSubviews.indexOf(this)
{
removeFromSuperview()
superview.insertArrangedSubview(blurOverlay, atIndex: index)
}
else
{
blurOverlay.frame.origin = frame.origin
UIView.transitionFromView(this,
toView: blurOverlay,
duration: 0.2,
options: UIViewAnimationOptions.CurveEaseIn,
completion: nil)
}
objc_setAssociatedObject(this,
&BlurableKey.blurable,
blurOverlay,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
func unBlur()
{
guard let this = self as? UIView,
blurOverlay = objc_getAssociatedObject(self as? UIView, &BlurableKey.blurable) as? BlurOverlay else
{
return
}
if let superview = blurOverlay.superview as? UIStackView,
index = (blurOverlay.superview as! UIStackView).arrangedSubviews.indexOf(blurOverlay)
{
blurOverlay.removeFromSuperview()
superview.insertArrangedSubview(this, atIndex: index)
}
else
{
this.frame.origin = blurOverlay.frame.origin
UIView.transitionFromView(blurOverlay,
toView: this,
duration: 0.2,
options: UIViewAnimationOptions.CurveEaseIn,
completion: nil)
}
objc_setAssociatedObject(this,
&BlurableKey.blurable,
nil,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
var isBlurred: Bool
{
return objc_getAssociatedObject(self as? UIView, &BlurableKey.blurable) is BlurOverlay
}
}
extension UIView: Blurable
{
}
class BlurOverlay: UIImageView
{
}
struct BlurableKey
{
static var blurable = "blurable"
}
Swift 4.x
extension UIView {
struct BlurableKey {
static var blurable = "blurable"
}
func blur(radius: CGFloat) {
guard let superview = superview else { return }
UIGraphicsBeginImageContextWithOptions(CGSize(width: frame.width, height: frame.height), false, 1)
layer.render(in: UIGraphicsGetCurrentContext()!)
guard let image = UIGraphicsGetImageFromCurrentImageContext() else { return }
UIGraphicsEndImageContext()
guard let blur = CIFilter(name: "CIGaussianBlur") else { return }
blur.setValue(CIImage(image: image), forKey: kCIInputImageKey)
blur.setValue(radius, forKey: kCIInputRadiusKey)
let ciContext = CIContext(options: nil)
guard let result = blur.value(forKey: kCIOutputImageKey) as? CIImage else { return }
let boundingRect = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
guard let cgImage = ciContext.createCGImage(result, from: boundingRect) else { return }
let filteredImage = UIImage(cgImage: cgImage)
let blurOverlay = UIImageView()
blurOverlay.frame = boundingRect
blurOverlay.image = filteredImage
blurOverlay.contentMode = UIViewContentMode.left
if let stackView = superview as? UIStackView, let index = stackView.arrangedSubviews.index(of: self) {
removeFromSuperview()
stackView.insertArrangedSubview(blurOverlay, at: index)
} else {
blurOverlay.frame.origin = frame.origin
UIView.transition(from: self,
to: blurOverlay,
duration: 0.2,
options: UIViewAnimationOptions.curveEaseIn,
completion: nil)
}
objc_setAssociatedObject(self,
&BlurableKey.blurable,
blurOverlay,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
func unBlur() {
guard let blurOverlay = objc_getAssociatedObject(self, &BlurableKey.blurable) as? UIImageView else { return }
if let stackView = blurOverlay.superview as? UIStackView, let index = stackView.arrangedSubviews.index(of: blurOverlay) {
blurOverlay.removeFromSuperview()
stackView.insertArrangedSubview(self, at: index)
} else {
frame.origin = blurOverlay.frame.origin
UIView.transition(from: blurOverlay,
to: self,
duration: 0.2,
options: UIViewAnimationOptions.curveEaseIn,
completion: nil)
}
objc_setAssociatedObject(self,
&BlurableKey.blurable,
nil,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
var isBlurred: Bool {
return objc_getAssociatedObject(self, &BlurableKey.blurable) is UIImageView
}
}
The usage is for example:
segmentedControl.unBlur()
segmentedControl.blur(blurRadius: 2)
This is the source of the project Blurable.
You can find more detail in his GitHub project here

Add blur view to label?

How can I add a blur view to a label? The label is in front of a UIImage and I wanted the background of the label to be blurred, so that the user can read the text better. I get the Blur effect inside the bounds of the label, but the text itself disappears (maybe also gets blurred, idk why). I also tried to add a label programmatically, but I didn't get it working. I'm thankful for any kind of help!
let blur = UIBlurEffect(style: .Light)
let blurView = UIVisualEffectView(effect: blur)
blurView.frame = findATeamLabel.bounds
findATeamLabel.addSubview(blurView)
You can make your own BlurredLabel which can blur/unblur its text. Through a CoreImage blur filter you take the text of the label, blur it in an image, and display that image on top of the label.
class BlurredLabel: UILabel {
func blur(_ blurRadius: Double = 2.5) {
let blurredImage = getBlurryImage(blurRadius)
let blurredImageView = UIImageView(image: blurredImage)
blurredImageView.translatesAutoresizingMaskIntoConstraints = false
blurredImageView.tag = 100
blurredImageView.contentMode = .center
blurredImageView.backgroundColor = .white
addSubview(blurredImageView)
NSLayoutConstraint.activate([
blurredImageView.centerXAnchor.constraint(equalTo: centerXAnchor),
blurredImageView.centerYAnchor.constraint(equalTo: centerYAnchor)
])
}
func unblur() {
subviews.forEach { subview in
if subview.tag == 100 {
subview.removeFromSuperview()
}
}
}
private func getBlurryImage(_ blurRadius: Double = 2.5) -> UIImage? {
UIGraphicsBeginImageContext(bounds.size)
layer.render(in: UIGraphicsGetCurrentContext()!)
guard let image = UIGraphicsGetImageFromCurrentImageContext(),
let blurFilter = CIFilter(name: "CIGaussianBlur") else {
UIGraphicsEndImageContext()
return nil
}
UIGraphicsEndImageContext()
blurFilter.setDefaults()
blurFilter.setValue(CIImage(image: image), forKey: kCIInputImageKey)
blurFilter.setValue(blurRadius, forKey: kCIInputRadiusKey)
var convertedImage: UIImage?
let context = CIContext(options: nil)
if let blurOutputImage = blurFilter.outputImage,
let cgImage = context.createCGImage(blurOutputImage, from: blurOutputImage.extent) {
convertedImage = UIImage(cgImage: cgImage)
}
return convertedImage
}
}
PS: Please make sure to improve this component as of your requirements (for example avoid blurring if already blurred or you could remove the current blurred and apply the blurred again if text has changed).
PSPS: Take into consideration also that applying blur to something makes its content bleeds out, so either set clipsToBounds = false to the BlurredLabel or find out other way to accomplish your visual effect in order to avoid the blurred image looks like is not in same position as the label unblurred text that was previously.
To use it you can simply create a BlurredLabel:
let blurredLabel = BlurredLabel()
blurredLabel.text = "56.00 €"
And on some button tap maybe you could achieve blurring as of blurredLabel.blur() and unblurring as of blurredLabel.unblur().
This is the output achieved with blur() through a blurRadius of 2.5:
To read more about Gaussian Blur, there is a good article on Wikipedia: https://en.wikipedia.org/wiki/Gaussian_blur
You could try sending it to the back of the view hierarchy for the label. Try
findATeamLabel.sendSubviewToBack(blurView)
Swift 5 - Blur as UIView extension
extension UIView {
struct BlurableKey {
static var blurable = "blurable"
}
func blur(radius: CGFloat) {
guard superview != nil else { return }
UIGraphicsBeginImageContextWithOptions(CGSize(width: frame.width, height: frame.height), false, 1)
layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard
let blur = CIFilter(name: "CIGaussianBlur"),
let image = image
else {
return
}
blur.setValue(CIImage(image: image), forKey: kCIInputImageKey)
blur.setValue(radius, forKey: kCIInputRadiusKey)
let ciContext = CIContext(options: nil)
let boundingRect = CGRect(
x:0,
y: 0,
width: frame.width,
height: frame.height
)
guard
let result = blur.value(forKey: kCIOutputImageKey) as? CIImage,
let cgImage = ciContext.createCGImage(result, from: boundingRect)
else {
return
}
let blurOverlay = UIImageView()
blurOverlay.frame = boundingRect
blurOverlay.image = UIImage(cgImage: cgImage)
blurOverlay.contentMode = .left
addSubview(blurOverlay)
objc_setAssociatedObject(
self,
&BlurableKey.blurable,
blurOverlay,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN
)
}
func unBlur() {
guard
let blurOverlay = objc_getAssociatedObject(self, &BlurableKey.blurable) as? UIImageView
else {
return
}
blurOverlay.removeFromSuperview()
objc_setAssociatedObject(
self,
&BlurableKey.blurable,
nil,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN
)
}
var isBlurred: Bool {
return objc_getAssociatedObject(self, &BlurableKey.blurable) is UIImageView
}
}
I got it working by adding just a View behind the label (the label is NOT inside that view, just in front of it). Then I added the blur effect to the view... I still think there should be an easier way.
None of the answers worked for me, the accepted answer dont work with background of different color of white, or label color different of black based on the comments it goes to another question yet the answer made the blur move to the right a lot. So after some reading adjusting the CGRect on the result image.
class BlurredLabel: UILabel {
var isBlurring = false {
didSet {
setNeedsDisplay()
}
}
var blurRadius: Double = 8 {
didSet {
blurFilter?.setValue(blurRadius, forKey: kCIInputRadiusKey)
}
}
lazy var blurFilter: CIFilter? = {
let blurFilter = CIFilter(name: "CIGaussianBlur")
blurFilter?.setDefaults()
blurFilter?.setValue(blurRadius, forKey: kCIInputRadiusKey)
return blurFilter
}()
override init(frame: CGRect) {
super.init(frame: frame)
layer.isOpaque = false
layer.needsDisplayOnBoundsChange = true
layer.contentsScale = UIScreen.main.scale
layer.contentsGravity = .center
isOpaque = false
isUserInteractionEnabled = false
contentMode = .redraw
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func display(_ layer: CALayer) {
let bounds = layer.bounds
guard !bounds.isEmpty && bounds.size.width < CGFloat(UINT16_MAX) else {
layer.contents = nil
return
}
UIGraphicsBeginImageContextWithOptions(layer.bounds.size, layer.isOpaque, layer.contentsScale)
if let ctx = UIGraphicsGetCurrentContext() {
self.layer.draw(in: ctx)
var image = UIGraphicsGetImageFromCurrentImageContext()?.cgImage
if isBlurring {
blurFilter?.setValue(CIImage(cgImage: image!), forKey: kCIInputImageKey)
let ciContext = CIContext(cgContext: ctx, options: nil)
if let blurOutputImage = blurFilter?.outputImage {
let boundingRect = CGRect(
x:0,
y: blurOutputImage.extent.minY,
width: blurOutputImage.extent.width,
height: blurOutputImage.extent.height
)
image = ciContext.createCGImage(blurOutputImage, from: boundingRect)
}
}
layer.contents = image
}
UIGraphicsEndImageContext()
}
}

Resources