DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • SwiftData Dependency Injection in SwiftUI Application
  • HLS Streaming With AVKit and Swift UI for iOS and tvOS
  • Matter vs. Thread - A Head-to-Head Comparison!
  • What Is IoT Gateway? Is It Important

Trending

  • How To Deploy Helidon Application to Kubernetes With Kubernetes Maven Plugin
  • A Better Web3 Experience: Account Abstraction From Flow (Part 2)
  • DevSecOps: Integrating Security Into Your DevOps Workflow
  • Top 7 Best Practices DevSecOps Team Must Implement in the CI/CD Process
  1. DZone
  2. Coding
  3. Frameworks
  4. Applying Gaussian Blur to UIViews with Swift Protocol Extensions

Applying Gaussian Blur to UIViews with Swift Protocol Extensions

Simon Gladman user avatar by
Simon Gladman
·
Sep. 21, 15 · Tutorial
Like (2)
Save
Tweet
Share
13.52K Views

Join the DZone community and get the full member experience.

Join For Free


Here's a fun little experiment showing the power of Swift's Protocol Extensions to apply a CIGaussianBlur Core Image filter to any UIView with no developer overhead. The code could be extended to apply any Core Image filter such as a half tone screen or colour adjustment.


Blurable is a simple protocol that borrows some of the methods and variables from a UIView:

 var layer: CALayer { get }
    var subviews: [UIView] { get }
    var frame: CGRect { get }

    func addSubview(view: UIView)

    func bringSubviewToFront(view: UIView)


...and adds a few of its own:



Obviously, just being a protocol, it doesn't do much on its own. However, by adding an extension, I can introduce default functionality. Furthermore, by extending UIView to implement Blurable, every component from a segmented control to a horizontal slider can be blurred:


    

extension UIView: Blurable

    {



    }



The Mechanics of Blurable

Getting a blurred representation of a UIView is pretty simple: I need to begin an image context, use the view's layer's renderInContext method to render into the context and then get a UIImage from the context:


    UIGraphicsBeginImageContextWithOptions(CGSize(width: frame.width, height: frame.height), false, 1)



    layer.renderInContext(UIGraphicsGetCurrentContext()!)



    let image = UIGraphicsGetImageFromCurrentImageContext()







    UIGraphicsEndImageContext();


Once I have the image populated, it's a fairly standard workflow to apply a Gaussian blur to it:


    guard let blur = CIFilter(name: "CIGaussianBlur") 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: -blurRadius * 4,

        y: -blurRadius * 4,

        width: frame.width + (blurRadius * 8),

        height: frame.height + (blurRadius * 8))



    let cgImage = ciContext.createCGImage(result, fromRect: boundingRect)







    let filteredImage = UIImage(CGImage: cgImage)


A blurred image will be larger than its input image, so I need to be explicit about the size I require in createCGImage.


The next step is to add a UIImageView to my view and hide all the other views. I've subclassed UIImageView to BlurOverlay so that when it comes to removing it, I can be sure I'm not removing an existing UIImageView: 


 let blurOverlay = BlurOverlay()
    blurOverlay.frame = boundingRect

    blurOverlay.image = filteredImage

    subviews.forEach{ $0.hidden = true }


    addSubview(blurOverlay)



When it comes to de-blurring, I want to ensure the last subview is one of my BlurOverlay  remove it and unhide the existing views:

  func unBlur()
    {
        if let blurOverlay = subviews.last as? BlurOverlay
        {
            blurOverlay.removeFromSuperview()

            subviews.forEach{ $0.hidden = false }
        }

    }



Finally, to see if a UIView is currently blurred, I just need to see if its last subview is a BlurOverlay:


  var isBlurred: Bool
  {
      return subviews.last is BlurOverlay
  }


Blurring a UIView

To blur and de-blur, just invoke blur() and unBlur() on an UIView:


    segmentedControl.unBlur()
    segmentedControl.blur(blurRadius: 2)


Source Code

As always, the source code for this project is available at my GitHub repository here. Enjoy!




Protocol (object-oriented programming) Gaussian (software) Swift (programming language)

Published at DZone with permission of Simon Gladman, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • SwiftData Dependency Injection in SwiftUI Application
  • HLS Streaming With AVKit and Swift UI for iOS and tvOS
  • Matter vs. Thread - A Head-to-Head Comparison!
  • What Is IoT Gateway? Is It Important

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: