I am developing an application which can tint colors in an image and export it.
I have added 3 versions of an image asset to my Assets.xcassets folder. These are 3 different sizes of the same image, namely: image1.png image1@2x.png image1@3x.png with respective sizes: 256x341, 512x683, 768x1024 pixels.
I have created a UIImageView
on my storyboard called myImage and assigned image1 to myImage via storyboard->utilities->attributes inspector-> Image View -> Image.
I am trying to use the following tintWithColor
function as a UIImage
extension to change the color of this image.
extension UIImage {
func tintWithColor(color:UIColor)->UIImage {
UIGraphicsBeginImageContext(self.size)
let context = UIGraphicsGetCurrentContext()
self.drawAtPoint(CGPoint(x: 0, y: 0))
CGContextSaveGState(context)
// flip the image
CGContextScaleCTM(context, 1.0, -1.0)
CGContextTranslateCTM(context, 0.0, -self.size.height)
// multiply blend mode
CGContextSetBlendMode(context, CGBlendMode.Multiply)
let rect = CGRectMake(0, 0, self.size.width, self.size.height)
CGContextClipToMask(context, rect, self.CGImage)
color.setFill()
CGContextFillRect(context, rect)
CGContextRestoreGState(context)
// create uiimage
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
As I am testing this function on my viewDidLoad()
to change the color of myImage.image
as below, I see that (on whatever device I am using) the width and height of my originalImage
is always 256 x 341,5
override func viewDidLoad() {
super.viewDidLoad()
let originalImage = myImage.image
print("LOG: original image width: \(originalImage!.size.width) height: \(originalImage!.size.height)")
let tintedImage = originalImage!.tintWithColor(UIColor(hue: 300/360, saturation: 0.70, brightness: 0.70, alpha: 0.6))
myImage.image = tintedImage
// Do any additional setup after loading the view.
}
If I don't apply these changes on my image, the quality of my image on an iPhone 6 (4,7") device looks as below:
If I apply the tintWithColor
and then reassign the resulting image to my imageView
the quality seems to drop, lines smoothen, as can be seen below:
Is there a way to avoid this quality loss? Eventually I will be exporting the high quality image, so I would like to apply this color tint function on the high quality version of this image.
Thank you.
UIGraphicsBeginImageContextWithOptions(CGSizeMake(self.size.width, self.size.height), false, 3.0)
should work