Set UIImage color - ios

I am on swift 4, and my goal is to change the color of a system UIImage in code. I declare the image with
let defaultImage = UIImage(systemName: "person.circle.fill")
But when I change its tint color with:
let grayDefaultImage = defaultImage?.withTintColor(.gray)
The grayDefaultImage still display the standard blue color. Next I use an extension
//MARK: -UIImage extension
extension UIImage {
/// #Todo: this blurs the image for some reason
func imageWithColor(color: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
color.setFill()
let context = UIGraphicsGetCurrentContext()
context?.translateBy(x: 0, y: self.size.height)
context?.scaleBy(x: 1.0, y: -1.0)
context?.setBlendMode(CGBlendMode.normal)
let rect = CGRect(origin: .zero, size: CGSize(width: self.size.width, height: self.size.height))
context?.clip(to: rect, mask: self.cgImage!)
context?.fill(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
And the image renders in a very "pixelated" or "low res" form.

withTintColor(_:) say: The new image uses the same rendering mode as the original image.
So if original image's rendering mode is .alwaysTemplate, means image will ignoring its color information. you need set mode to .alwaysOriginal:
defaultImage?.withTintColor(.gray, renderingMode: .alwaysOriginal)

Related

How to apply scale when drawing and composing UIImage

I have the following functions.
extension UIImage
{
var width: CGFloat
{
return size.width
}
var height: CGFloat
{
return size.height
}
private static func circularImage(diameter: CGFloat, color: UIColor) -> UIImage
{
UIGraphicsBeginImageContextWithOptions(CGSize(width: diameter, height: diameter), false, 0)
let context = UIGraphicsGetCurrentContext()!
context.saveGState()
let rect = CGRect(x: 0, y: 0, width: diameter, height: diameter)
context.setFillColor(color.cgColor)
context.fillEllipse(in: rect)
context.restoreGState()
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
private func addCentered(image: UIImage, tintColor: UIColor) -> UIImage
{
let topImage = image.withTintColor(tintColor, renderingMode: .alwaysTemplate)
let bottomImage = self
UIGraphicsBeginImageContext(size)
let bottomRect = CGRect(x: 0, y: 0, width: bottomImage.width, height: bottomImage.height)
bottomImage.draw(in: bottomRect)
let topRect = CGRect(x: (bottomImage.width - topImage.width) / 2.0,
y: (bottomImage.height - topImage.height) / 2.0,
width: topImage.width,
height: topImage.height)
topImage.draw(in: topRect, blendMode: .normal, alpha: 1.0)
let mergedImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return mergedImage
}
}
They work fine, but how do I properly apply UIScreen.main.scale to support retina screens?
I've looked at what's been done here but can't figure it out yet.
Any ideas?
Accessing UIScreen.main.scale itself is a bit problematic, as you have to access it only from main thread (while you usually want to put a heavier image processing on a background thread). So I suggest one of these ways instead.
First of all, you can replace UIGraphicsBeginImageContext(size) with
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
The last argument (0.0) is a scale, and based on docs "if you specify a value of 0.0, the scale factor is set to the scale factor of the device’s main screen."
If instead you want to retain original image's scale on resulting UIImage, you can do this: after topImage.draw, instead of getting the UIImage with UIGraphicsGetImageFromCurrentImageContext, get CGImage with
let cgImage = context.makeImage()
and then construct UIImage with the scale and orientation of the original image (as opposed to defaults)
let mergedImage = UIImage(
cgImage: cgImage,
scale: image.scale,
orientation: image.opientation)

How to set tint color of an Image

let tintedImage = #imageLiteral(resourceName: "user")
pictureImageView?.image = mainCircleImage.overlayed(with: tintedImage,color: UIColor.orange)
extension UIImage {
func overlayed(with overlay: UIImage,color:UIColor) -> UIImage? {
defer {
UIGraphicsEndImageContext()
}
UIGraphicsBeginImageContextWithOptions(size, false, scale)
self.draw(in: CGRect(origin: CGPoint.zero, size: size))
let tintedOverlay = overlay.tintedImageWithColor(color: color)
tintedOverlay.draw(in: CGRect(origin: CGPoint.zero, size: size))
if let image = UIGraphicsGetImageFromCurrentImageContext() {
return image
}
return nil
}
func tint(color: UIColor, blendMode: CGBlendMode) -> UIImage
{
let drawRect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(size, false, scale)
let context = UIGraphicsGetCurrentContext()
context!.scaleBy(x: 1.0, y: -1.0)
context!.translateBy(x: 0.0, y: -self.size.height)
context!.clip(to: drawRect, mask: cgImage!)
color.setFill()
UIRectFill(drawRect)
draw(in: drawRect, blendMode: blendMode, alpha: 1.0)
let tintedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return tintedImage!
}
func tintedImageWithColor(color: UIColor) -> UIImage
{
return self.tint(color: color, blendMode: CGBlendMode.multiply)
}
}
I have updated my question according to possible answer
Here is my code for the changing the icon color. In some reason my user icon is not fully filling its color when i change the tint color.
I had added 2 more methods to your extension of UIImagefor tint an Image and added some changes in your overlayed method
extension UIImage {
func overlayed(with overlay: UIImage,color:UIColor) -> UIImage? {
defer {
UIGraphicsEndImageContext()
}
UIGraphicsBeginImageContextWithOptions(size, false, scale)
self.draw(in: CGRect(origin: CGPoint.zero, size: size))
let tintedOverlay = overlay.tinted(color: color)
tintedOverlay.draw(in: CGRect(origin: CGPoint.zero, size: size), blendMode: .multiply, alpha: 1.0)
if let image = UIGraphicsGetImageFromCurrentImageContext() {
return image
}
return nil
}
func tinted(color: UIColor) -> UIImage
{
UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen.main.scale)
let context = UIGraphicsGetCurrentContext()
color.setFill()
context!.translateBy(x: 0, y: self.size.height)
context!.scaleBy(x: 1.0, y: -1.0)
context!.setBlendMode(CGBlendMode.colorBurn)
let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
context!.draw(self.cgImage!, in: rect)
context!.setBlendMode(CGBlendMode.sourceIn)
context!.addRect(rect)
context!.drawPath(using: CGPathDrawingMode.fill)
let coloredImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return coloredImage!
}
}
The content of Tinted method is from this question How can I color a UIImage in Swift?
answer provided by #HR
Use It
let mainCircleImage = UIImage(named: "actions_menu_edit")?
let tintedImage = UIImage(named: "actions_menu_add")
pictureImageView?.image = mainCircleImage?.overlayed(with: tintedImage!,color: UIColor.red)
UPDATED
Result with the last update

Tab Bar Button color in Swift 3?

In Swift 2 I used a User Defined Runtime Attribute in Storyboard with a key path of tintColor to change the tab bar item icon colors. However, it looks like tintColor was removed with Swift 3. How can I change the selected color of the tab bar items in a tab bar controller in Swift 3?
Thanks!
EDIT: Attached screenshot
Use tabBarItem.setTitleTextAttributes to change text color of individual bar items.
Put this in viewDidLoad method of each tab:
self.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red()], for:.selected)
To change the icon and text tint color together a simple solution is to change the tabBar tint color in viewWillAppear method of each tab:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tabBarController?.tabBar.tintColor = UIColor.red()
}
Another solution to change the image tint color is to create an extension for UIImage and use it to change the selected image with custom tint:
extension UIImage {
func tabBarImageWithCustomTint(tintColor: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
let context: CGContext = UIGraphicsGetCurrentContext()!
context.translate(x: 0, y: self.size.height)
context.scale(x: 1.0, y: -1.0)
context.setBlendMode(CGBlendMode.normal)
let rect: CGRect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
context.clipToMask(rect, mask: self.cgImage!)
tintColor.setFill()
context.fill(rect)
var newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
newImage = newImage.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
return newImage
}
}
Use this code to change the selected image:
self.tabBarItem.selectedImage = self.tabBarItem.selectedImage?.tabBarImageWithCustomTint(tintColor: UIColor.red())
The latest code as par Swift 3 is
extension UIImage {
func tabBarImageWithCustomTint(tintColor: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
let context: CGContext = UIGraphicsGetCurrentContext()!
context.translateBy(x: 0, y: self.size.height)
context.scaleBy(x: 1.0, y: -1.0)
context.setBlendMode(CGBlendMode.normal)
let rect: CGRect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
context.clip(to: rect, mask: self.cgImage!)
tintColor.setFill()
context.fill(rect)
var newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
newImage = newImage.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
return newImage
}
}

Swift UIView with multiply effect

What I've been trying to achieve for a couple of hours is something like the following:
I would like to have a UIImage in the background and then preferably a UIView with a background color of red with some kind of multiply effect (the red area). Is this possible? I've seen a few extensions for UIImage that tints them, but that would only work if I wanted my WHOLE image to have a red multiply color effect.
Thanks
You could just add a red UIView to the top of your UIImageView. Adjust the alpha to make it transparent:
let someView = UIView(frame: someImageView.frame)
someView.backgroundColor = UIColor(colorLiteralRed: 255.0/255.0, green: 0, blue: 0, alpha: 0.5)
someImageView.addSubview(someView)
Using a multiply instead:
let img = UIImage(named: “background”)
let img2 = UIImage(named: “effect”) //Make sure this is your red image same size as the background
let rect = CGRect(x: 0, y: 0, width: img.size.width, height: img.size.height)
UIGraphicsBeginImageContextWithOptions(img.size, true, 0)
let context = UIGraphicsGetCurrentContext()
// fill the background with white so that translucent colors get lighter
CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor)
CGContextFillRect(context, rect)
img.drawInRect(rect, blendMode: .Normal, alpha: 1)
img2.drawInRect(rect, blendMode: .Multiply, alpha: 1)
// grab the finished image and return it
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
Swift 3 Extension (thx to #Kex):
extension UIImage{
class func multiply(image:UIImage, color:UIColor) -> UIImage? {
let rect = CGRect(origin: .zero, size: image.size)
//image colored
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.setFill()
UIRectFill(rect)
let coloredImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
//image multiply
UIGraphicsBeginImageContextWithOptions(image.size, true, 0)
let context = UIGraphicsGetCurrentContext()
// fill the background with white so that translucent colors get lighter
context!.setFillColor(UIColor.white.cgColor)
context!.fill(rect)
image.draw(in: rect, blendMode: .normal, alpha: 1)
coloredImage?.draw(in: rect, blendMode: .multiply, alpha: 1)
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
}
Example:
let image = UIImage.multiply(image: sourceImage, color: UIColor.red)
With iOS10 you can now use UIGraphicsImageRenderer to add a partial multiply effect as easy as this:
extension UIImage {
func tinted(_ color: UIColor, percentageFromBottom: CGFloat) -> UIImage? {
let imageRect = CGRect(origin: .zero, size: size)
let colorRect = CGRect(x: 0, y: (1.0 - percentageFromBottom) * size.height, width: size.width, height: percentageFromBottom * size.height)
let renderer = UIGraphicsImageRenderer(size: size)
let tintedImage = renderer.image { context in
color.set()
context.fill(colorRect)
draw(in: imageRect, blendMode: .multiply, alpha: 1)
}
return tintedImage
}
}
You can then use it like this to multiply the lower third of the original with a red multiply:
UIImage(named: "trees")?.tinted(.red, percentageFromBottom: 0.33)
Which results in this:

I have a png file with no background, how can I create a clear color background for this image in iOS?

So I understand that a UIImage inherently doesn't have a background. As many of us know, a lot of PNG files don't have a background Color thus making it clear. I'm attempting to upload a png file that doesn't have a background color, thus a clear color. Yes, I know I can set the background Color myself in adobe or sketch, but I'm assuming that other users don't know how to do this.
Here is a screenshot of the png that I have created:
As you can see, it's just two lines that are unioned together so there's no background set.
Now below is a screenshot of the aftermath of using the imagePicker to choose this png image from my photo roll.
Notice that the area that is supposed to be transparent is actually black. I want to color in the black part and make it actually clearColor instead and keep the green cross as it is. Now, I'm not sure if the black color is actually even a black color because perhaps it's just empty space. Can I fill in the empty black space and turn it into a clear color?
Here's my code right now that isn't working very well:
func overlayImage(image: UIImage, color: UIColor) -> UIImage? {
let rect = CGRectMake(0, 0, image.size.width, image.size.height)
let backgroundView = UIView(frame: rect)
backgroundView.backgroundColor = color
UIGraphicsBeginImageContext(rect.size)
let gcSize: CGSize = backgroundView.frame.size
UIGraphicsBeginImageContext(gcSize)
let context: CGContextRef = UIGraphicsGetCurrentContext()!
backgroundView.layer.renderInContext(context)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
Any help in either obj-C or Swift would be greatly appreciated.
I got rid of the overlay method above and am using the code below:
Updated with new code that still doesn't work
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
scaleImage(overlayImage(image, color: UIColor.clearColor()))
}
func scaleImageAndAddAugmented(image: UIImage?) {
let rect = CGRectMake(0, 0, image!.size.width, image!.size.height)
let backgroundView = UIView(frame: rect)
backgroundView.backgroundColor = UIColor.clearColor()
let size = CGSizeApplyAffineTransform(image!.size, CGAffineTransformMakeScale(0.25, 0.25))
let hasAlpha = false
let scale: CGFloat = 0.0
UIGraphicsBeginImageContextWithOptions(size, !hasAlpha, scale)
image!.drawInRect(CGRect(origin: CGPointZero, size: size))
let context = CGBitmapContextCreate(nil, Int(image!.size.width), Int(image!.size.height), 8, 0, CGColorSpaceCreateDeviceRGB(), CGImageAlphaInfo.PremultipliedLast.rawValue)
let myGeneratedImage = CGBitmapContextCreateImage(context)
CGContextDrawImage(context, rect, myGeneratedImage)
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.dismissViewControllerAnimated(true, completion: nil)
// set image below
}
It seems a bit of excess work to use UIGraphicsGetImageFromCurrentImageContext to generate an image from context, when you can just create an image from a file.
As first mentioned it is required to have Opaque = NO:
UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
My bet is its the image itself, because the whole thing is faded.
Make 100% certain that the passed colour is a clear colour for:
backgroundView.backgroundColor = color
You could create a bitmap context and use that instead:
CGContextRef context = CGBitmapContextCreate(NULL,
width,
height,
8,
0,
rgbColorSpace,
kCGImageAlphaPremultipliedLast);
Rather than using the current context and you can use:
myGeneratedImage = CGBitmapContextCreateImage(context)
Drawing is easy as pie:
CGContextDrawImage(realContext,bounds,myGeneratedImage)
Swift code below:
func scaleImage(image: UIImage?) {
if let image = image {
let rect = CGRectMake(0, 0, image.size.width, image.size.height)
let size: CGSize = CGSizeApplyAffineTransform(image.size, CGAffineTransformMakeScale(0.25, 0.25))
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
image.drawInRect(CGRect(origin: CGPointZero, size: size))
let context = CGBitmapContextCreate(nil, Int(image.size.width), Int(image.size.height), 8, 0, CGColorSpaceCreateDeviceRGB(), CGImageAlphaInfo.PremultipliedLast.rawValue)
let myGeneratedImage = CGBitmapContextCreateImage(context)
CGContextDrawImage(context, rect, myGeneratedImage)
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
}

Resources