Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: create an darker version of UIImage and leave transparent pixels unchanged?

I found

Create new UIImage by adding shadow to existing UIImage

and

UIImage, is there an easy way to make it darker or all black

But the selected answers do not work for me.

I have an UIImage, which may have some transparent pixels in it, I need to create a new UIImage with non-transparent pixels darkened, is there any way to do this? I was thinking of using UIBezierPath but I don't know how to do it for only non-transparent pixels.

like image 756
hzxu Avatar asked Sep 12 '12 02:09

hzxu


People also ask

What is the difference between a UIImage and a UIImageView?

UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .

What is UIImage?

An object that manages image data in your app.


1 Answers

Here's a quick Swift version, using a CIExposureAdjust CIFilter :)

  // Get the original image and set up the CIExposureAdjust filter
  guard let originalImage = UIImage(named: "myImage"),
    let inputImage = CIImage(image: originalImage),
    let filter = CIFilter(name: "CIExposureAdjust") else { return }

  // The inputEV value on the CIFilter adjusts exposure (negative values darken, positive values brighten)
  filter.setValue(inputImage, forKey: "inputImage")
  filter.setValue(-2.0, forKey: "inputEV")

  // Break early if the filter was not a success (.outputImage is optional in Swift)
  guard let filteredImage = filter.outputImage else { return }

  let context = CIContext(options: nil)
  let outputImage = UIImage(CGImage: context.createCGImage(filteredImage, fromRect: filteredImage.extent))

  myImageView.image = outputImage // use the filtered UIImage as required.
like image 158
worthbak Avatar answered Sep 22 '22 08:09

worthbak