2013-04-08 31 views
15

Tôi đang cố tạo UIImage từ giá trị UIColor này mà tôi có. UIImage đang được tạo, nhưng giá trị alpha bị mất. Hình ảnh vẫn mờ đục. Tôi đang sử dụng đoạn mã sau:UIImage từ UIColor với 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 

Mà tôi gọi như vậy:

-(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]; 

} 

Bất kỳ ý tưởng những gì tôi đang thiếu?

Trả lời

15

Bạn đang tạo ngữ cảnh hình ảnh mờ đục.

Thay thế dòng này:

UIGraphicsBeginImageContext(rect.size); 

với:

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

Nó làm việc! Cảm ơn! :) –

2

Trong trường hợp ai đó tìm thấy câu hỏi này và họ đang tìm kiếm thi 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; 
       }