2014-02-22 2 views
1

UIBezierPath를 UIView 범주에서 사용하여 삼각형을 만들려고합니다. 삼각형은 보이지 않습니다. 또한 CGContextSetFillColorWithColor를 얻습니다. 그래서 내 질문에 UIView 범주를 사용하여 삼각형 또는 모든 경로를 만드는 방법입니다. ViewController.m에서 Demo ProjectUIView 범주에 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 

이 좋아 사용 : - 널 컨텍스트에 삼각형을 그리는 시도 UIBezierPath 당신의 의 UIView + Bubble.h 카테고리에서

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

답변

5

. 위와 같이 UIBezierPath를 사용하여 도형을 그리려면이 코드를 drawRect View 클래스의 메서드 내에 넣어야합니다.

반면에, 그릴 새로운 컨텍스트를 만들 수 있습니다.

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

같은 당신은 다음과 같이 당신의 makeBubble 방법을 수정할 수 있습니다 이 방법 내에서 customView.frame=rect;UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);으로 변경하십시오.

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

P.S.로 방법 RECT (CGRect) : 그리고 makeBubble 전화 직사각형에 따라 포인트를 계산하면 좋을 것입니다.

+0

@ x4h1d- 어떻게 UIGraphicsBeginImageContextWithOptions를 cgrect에 따라 동적으로 제공합니까? – iOS

+0

@ 존, 편집 부분을 참조하십시오. – x4h1d

+0

@ x4h1d- 고마워요. – iOS