Also, alle Antworten zusammenzufassen in einem hier ist der Drop-in-Verfahren, das perfekt von iOS 6
den ganzen Weg bis zu iOS 11
mit allen Arten Werke Bilder und Symbole:
+ (UIImage *)filledImageFrom:(UIImage *)source withColor:(UIColor *)color{
// begin a new image context, to draw our colored image onto with the right scale
UIGraphicsBeginImageContextWithOptions(source.size, NO, [UIScreen mainScreen].scale);
// get a reference to that context we created
CGContextRef context = UIGraphicsGetCurrentContext();
// set the fill color
[color setFill];
// translate/flip the graphics context (for transforming from CG* coords to UI* coords
CGContextTranslateCTM(context, 0, source.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextSetBlendMode(context, kCGBlendModeColorBurn);
CGRect rect = CGRectMake(0, 0, source.size.width, source.size.height);
CGContextDrawImage(context, rect, source.CGImage);
CGContextSetBlendMode(context, kCGBlendModeSourceIn);
CGContextAddRect(context, rect);
CGContextDrawPath(context,kCGPathFill);
// generate a new UIImage from the graphics context we drew onto
UIImage *coloredImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//return the color-burned image
return coloredImg;
}
Update: Swift 3-Version
func filledImage(source: UIImage, fillColor: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(source.size, false, UIScreen.main.scale)
let context = UIGraphicsGetCurrentContext()
fillColor.setFill()
context!.translateBy(x: 0, y: source.size.height)
context!.scaleBy(x: 1.0, y: -1.0)
context!.setBlendMode(CGBlendMode.colorBurn)
let rect = CGRect(x: 0, y: 0, width: source.size.width, height: source.size.height)
context!.draw(source.cgImage!, in: rect)
context!.setBlendMode(CGBlendMode.sourceIn)
context!.addRect(rect)
context!.drawPath(using: CGPathDrawingMode.fill)
let coloredImg : UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return coloredImg
}
Kannst du darüber sprechen, wo das eigentlich gemacht wird? Mache ich eine Unterklasse von UIImage? – davis
@DavisG. Der obige Code ist ein Beispiel für eine überschriebene drawRect: -Methode in einer UIView-Unterklasse. Es wäre sehr einfach, es zu ändern, um stattdessen einen Bitmap-Kontext zu verwenden. – rpetrich
@rpetrich Sollte das nicht '[[UIColor blackColor] setFill] 'sein, da du mehr füllst als streichelst? –