2013-04-08 19 views
15

Sto provando a creare un UIImage da questo valore UIColor che ho. UIImage viene creato, ma il valore alfa è perso. L'immagine rimane opaca. Sto usando il seguente codice:UIImmagine da UIColor con alpha

@implementation GetImage 

+ (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; 
} 

@end 

che io chiamo in questo modo:

-(void) setButtonColours{ 

    UIImage *img1, *img2; 

    UIColor *red = [UIColor colorWithRed:205.0/255.0 green:68.0/255.0 blue:51.0/255.0 alpha:1.0], 
    *blue = [UIColor colorWithRed:71.0/255.0 green:97.0/255.0 blue:151.0/255.0 alpha:1.0]; 

    img1 = [GetImage imageWithColor: blue andSize: self.dummyButton.frame.size]; 

    img2 = [GetImage imageWithColor: red andSize: self.dummyButton.frame.size]; 

    [self.dummyButton setBackgroundImage: img1 forState:UIControlStateNormal]; 
    [self.dummyButton setBackgroundImage: img2 forState:UIControlStateSelected]; 

} 

Qualche idea di cosa mi manca?

risposta

15

Si sta creando un contesto immagine opaco.

Sostituire questa linea:

UIGraphicsBeginImageContext(rect.size); 

con:

UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0); 
+0

ha funzionato! Grazie! :) –

2

Nel caso qualcuno trova questa domanda e sono alla ricerca per l'attuazione MonoTouch:

public class ColorRGBA 
     { 
      public float Red=0; 
      public float Green=0; 
      public float Blue=0; 
      public float Alpha=0; 

      public ColorRGBA (float red, float green, float blue, float alpha) 
      { 
       Red = red; 
       Green = green; 
       Blue = blue; 
       Alpha = alpha; 
      } 
     } 

//then from within a custom mt.d element 

private ColorRGBA color; 

    public override UITableViewCell GetCell (UITableView tv) 
       { 
        //create square with color 
        var imageSize = new SizeF(30, 30); 
        var imageSizeRectF = new RectangleF (0, 0, 30, 30); 
        UIGraphics.BeginImageContextWithOptions (imageSize, false, 0); 
        var context = UIGraphics.GetCurrentContext(); 
        context.SetFillColor (color.Red, color.Green, color.Blue, color.Alpha); 
        context.FillRect (imageSizeRectF); 
        var image = UIGraphics.GetImageFromCurrentImageContext(); 
        UIGraphics.EndImageContext(); 

        var cell = base.GetCell(tv); 
        cell.Accessory = UITableViewCellAccessory.DisclosureIndicator; 
        cell.ImageView.Image = image; 

        return cell; 
       } 
Problemi correlati