Sovrapporre un'UIImage con un colore?
Domanda
Sto tentando di aggiungere una sovrapposizione nera su alcune UIImage attuali (che sono bianche).Ho provato a utilizzare il seguente codice:
[[UIColor blackColor] set];
[image drawAtPoint:CGPointMake(0, 0) blendMode:kCGBlendModeOverlay alpha:1.0];
Ma non funziona, e sono abbastanza sicuro che il set non dovrebbe essere lì.
Soluzione
Dovrai agganciare il contesto a una maschera immagine e riempirlo di un colore solido:
- (void)drawRect:(CGRect)rect
{
CGRect bounds = [self bounds];
[[UIColor blackColor] set];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClipToMask(context, bounds, [myImage CGImage]);
CGContextFillRect(context, bounds);
}
Nota: myImage
dovrebbe essere una variabile di istanza che contiene un UIImage
. Non sono sicuro se prende la maschera dal canale alfa o l'intensità, quindi prova entrambi.
Altri suggerimenti
Quindi, per riassumere tutte le risposte in una, ecco il metodo drop-in che funziona perfettamente da iOS 6
fino a iOS 11
con tutti i tipi di immagini e icone:
+ (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;
}
Aggiornamento: versione Swift 3
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
}
Ho appena scritto un tutorial che ti aiuterà in questo. Il mio approccio ti dà una copia di un UIImage, con le alterazioni di colore che desideri. L'approccio di rpetrich è eccezionale, ma richiede la creazione di una sottoclasse. Il mio approccio è solo alcune righe di codice che possono essere inserite ovunque ne abbiate bisogno. http://coffeeshopped.com/2010/09/ iphone-how-to-dinamico-color-a-UIImage
NSString *name = @"badge.png";
UIImage *img = [UIImage imageNamed:name];
// begin a new image context, to draw our colored image onto
UIGraphicsBeginImageContext(img.size);
// 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, img.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
// set the blend mode to color burn, and the original image
CGContextSetBlendMode(context, kCGBlendModeColorBurn);
CGRect rect = CGRectMake(0, 0, img.size.width, img.size.height);
CGContextDrawImage(context, rect, img.CGImage);
// set a mask that matches the shape of the image, then draw (color burn) a colored rectangle
CGContextClipToMask(context, rect, img.CGImage);
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;
Da iOS 7 esiste una soluzione molto più semplice:
UIImage* im = [UIImage imageNamed:@"blah"];
im = [im imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
[[UIColor blackColor] setFill];
[im drawInRect:rect];
Guarda questo metodo
+ (UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)size;
{
UIImage *img = nil;
CGRect rect = CGRectMake(0, 0, size.width, size.height);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context,
color.CGColor);
CGContextFillRect(context, rect);
img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
Oltre alla soluzione di rpetrich (che è fantastica tra l'altro - aiutami magnificamente), puoi anche sostituire la riga CGContextClipToMask con:
CGContextSetBlendMode(context, kCGBlendModeSourceIn); //this is the main bit!
È la modalità di fusione SourceIn che svolge il compito di mascherare il colore con qualunque cosa si trovi nel GetCurrentContext.
Ecco come farlo con Swift 3.0 e utilizzando le estensioni di UIImage. Super semplice.
public extension UIImage {
func filledImage(fillColor: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen.main.scale)
let context = UIGraphicsGetCurrentContext()!
fillColor.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 coloredImg : UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return coloredImg
}
}
Quindi eseguirlo semplicemente:
let image = UIImage(named: "image_name").filledImage(fillColor: UIColor.red)
-set
viene utilizzato per impostare il colore delle successive operazioni di disegno che non include i blits. Suggerisco come prima chiamata, visualizzando un altro (vuoto) UIView
sopra il tuo UIImageView
e impostando il colore di sfondo:
myView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.5];
Ovviamente dovresti usare i valori bianco e alfa che desideri.
Puoi farlo a livello di programmazione in Swift 4.x nel modo successivo:
imageView.image = UIImage(named: "imageName")?.withRenderingMode(.alwaysTemplate)
imageView.tintColor = .purple