2

我必须在 UIButton 上添加一个小红点。我使用此方法设置自定义 UIButton 的颜色:

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

然后我只需在这个按钮上添加一个简单的红点,大概是这样完成的:

+ (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 添加小红点的正确方法是什么?

4

1 回答 1

1

您正在抚摸一个超出您在此行中设置的上下文范围的椭圆:

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

为了让椭圆显示出来,它需要在你的上下文范围内,它的大小似乎是 1x1。

于 2012-05-03T12:44:28.407 回答