2011-12-05 36 views
3

我需要繪製一個矩形填充顏色及其邊框...... 矩形正確填充顏色,但外部邊框部分繪製,只是矩形的右側是畫!CGContextStrokeRect正在繪製矩形的一邊

生成的UIImage將在UITableViewCell的imageView中使用。

- (UIImage *)legendItemWithColor:(UIColor *)color 
{ 
    UIGraphicsBeginImageContext(self.view.frame.size); 
    CGContextRef context = UIGraphicsGetCurrentContext(); 

    CGRect outside = CGRectMake(128, 128, 128, 128); 
    CGRect legend = CGRectInset(outside, 1, 1); 

    NSLog(@"Outside: %@", NSStringFromCGRect(outside)); 
    NSLog(@"Legend: %@", NSStringFromCGRect(legend)); 

    CGContextSetFillColorWithColor(context, color.CGColor); 
    CGContextFillRect(context, legend); 

    CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor); 
    CGContextStrokeRect(context, outside); 

    UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    UIGraphicsPopContext(); 

    return img; 
} 
+0

我在模擬器上檢查了你的代碼,它很好。這就是說,我認爲這個問題可能與上下文邊界相關,它是'self.view.frame.size' –

+0

你可以嘗試在cellView.image = [self legendItemWithColor:[UIColor orangeColor]]的tableview中使用它; – Progeny

+0

那就不好了。然而,要解決它,你必須通過適當的CGSize到UIGraphicsBeginImageContext()而不是self.view.frame.size。我建議只傳遞你需要的尺寸,例如CGSizeMake(128 + 128 + 2,128 + 128 + 2)。然後它顯示OK –

回答

2

問題是,當你通過self.view.frame.size到UIGraphicsBeginImageContext(),然後在陣列中使用繪製的矩形,它是按比例縮小與邊界進行模糊處理。嘗試只傳遞你需要的尺寸,例如CGSizeMake(2 * 128 + 128 + 2,2 * 128 + 128 + 2)。然後它顯示ok