2012-05-03 6 views
2

我必須在UIButton中添加一個小紅點。我設置自定義顏色的UIButton使用這種方法:在Core Graphics中添加一個點到CGContext

+ (UIImage *) imageFromColor:(UIColor *)color { 
    CGRect rect = CGRectMake(0, 0, 1, 1); 
    UIGraphicsBeginImageContext(rect.size); 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSetFillColorWithColor(context, [color CGColor]); 
    // [[UIColor colorWithRed:222./255 green:227./255 blue: 229./255 alpha:1] CGColor]) ; 
    CGContextFillRect(context, rect); 
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    return img; 
} 

那我也只是一個簡單的紅點添加到該按鈕,這是assumably這樣做:

+ (UIImage *) addRedDot 
{ 
    CGRect rect = CGRectMake(0, 0, 1, 1); 
    UIGraphicsBeginImageContext(rect.size); 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSetFillColorWithColor(context, [[UIColor redColor] CGColor]); 
    // [[UIColor colorWithRed:222./255 green:227./255 blue: 229./255 alpha:1] CGColor]) ; 
    CGContextSetRGBStrokeColor(context, 1.0f, 0.0f, 0.0f, 1.0f); 

    CGContextSetLineWidth(context, 2.0); 
    CGContextStrokeEllipseInRect(context, CGRectMake(10, 11, 21, 21)); 

// CGContextFillRect(context, rect); 
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    return img; 
} 

但它只是返回黑白圖像.. 這個客戶端代碼:

if ([dateStringToAssign isEqualToString:[self dateToString:[NSDate date]]]) 
      { 

       [buttonToLay setBackgroundImage:[CommonUIUtility imageFromColor:[UIColor cyanColor]] 
            forState:UIControlStateNormal]; 


      } 
      if([dbm hasEventsForDate:buttonToLay.ownedDate]) 
      { 
       NSLog(@"Has events"); 
       [buttonToLay setBackgroundImage:[CommonUIUtility addRedDot] forState:UIControlStateNormal]; 

      } 

什麼是一個小紅點添加到現有CGContext上的正確方法?

回答

1

你撫摸着一個橢圓beyonds你在這一行建立了上下文的界限:

CGContextStrokeEllipseInRect(context, CGRectMake(10, 11, 21, 21));

爲了有橢圓形展現出來,它需要的範圍內的上下文,其大小似乎爲1x1。

+0

stll我沒有得到一個點,我只有一個填充顏色 –

+1

這是你的上下文的邊界只有1x1,所以*可以*繪製的唯一的東西是一個像素看起來像一個填充顏色。你需要用更大的尺寸實例化你的上下文(例如'UIGraphicsBeginImageContext(CGRectMake(0,0,50,50));' – Sean

+0

剛剛明白,謝謝 –

相關問題