2014-02-22 23 views
1

我想創建一個UIBezierPath在UIView類別中使用的三角形。但三角形沒有被顯示。也得到:CGContextSetFillColorWithColor。所以我的問題是如何使三角形或任何使用UIView類別的路徑。 Demo Project在UIView類別中創建一個UIBezierPath。不顯示

#import "UIView+Bubble.h" 
#import <QuartzCore/QuartzCore.h> 

@implementation UIView (Bubble) 

+(UIView *)makeBubble{ 
    UIView *customView = [[UIView alloc] init]; 
    customView.frame=CGRectMake(0, 0, 320, 500); 
    UIBezierPath *triangle = [UIBezierPath bezierPath]; 
    [triangle moveToPoint:CGPointMake(100, 0)]; 
    [triangle addLineToPoint:CGPointMake(0, 100)]; 
    [triangle addLineToPoint:CGPointMake(200, 100)]; 
    [triangle closePath]; 
    [[UIColor blackColor] setFill]; 
    [triangle fill]; 
    customView.layer.shadowPath = [triangle CGPath]; 
    return customView; 
} 
@end 

在ViewController.m使用它,如: -

- (void)viewDidLoad 
{ 
    UIView *helpBubble=[UIView makeBubble]; 
    [self.view addSubview:helpBubble]; 
} 

回答

5

在你的UIView + Bubble.h類別UIBezierPath嘗試畫上一個空的上下文三角形。如果你想使用上面的UIBezierPath來繪製形狀,你必須把這個代碼放入View類的drawRect方法中。

另一方面,您可以創建一個新的上下文來繪製。您可以修改makeBubble方法如下:

+(UIView *)makeBubble{ 
    // declare UIimageView, not UIView 
    UIImageView *customView = [[UIImageView alloc] init]; 
    customView.frame=CGRectMake(0, 0, 320, 500); 

    // create a new contex to draw 
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(200, 200), NO, 0); 

    UIBezierPath *triangle = [UIBezierPath bezierPath]; 
    [triangle moveToPoint:CGPointMake(100, 0)]; 
    [triangle addLineToPoint:CGPointMake(0, 100)]; 
    [triangle addLineToPoint:CGPointMake(200, 100)]; 
    [triangle closePath]; 
    [[UIColor blackColor] setFill]; 
    [triangle fill]; 

    customView.image = UIGraphicsGetImageFromCurrentImageContext(); 

    UIGraphicsEndImageContext(); 

    return customView; 
} 



編輯:

,使其動態,你可以通過一個的CGRect的說法,像

+(UIView *)makeBubble:(CGRect)rect 

也在此方法內更改爲customView.frame=rect;UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);。並調用makeBubble:(的CGRect)RECT方法

UIView *helpBubble=[UIView makeBubble:/*your desire rect*/]; 

附:如果你也根據矩形計算點數,那將會很好。

+0

@ x4h1d-如何根據cgrect給UIGraphicsBeginImageContextWithOptions動態。 – iOS

+0

@John,請參閱編輯部分。 – x4h1d

+0

@ x4h1d-非常感謝。 – iOS

相關問題