1. 程式人生 > >iOS重寫drawRect方法實現帶箭頭的View

iOS重寫drawRect方法實現帶箭頭的View

hat oid line wid addition arrow memory alt ins

創建一個UIView的子類,重寫drawRect方法可以實現不規則形狀的View,這裏提供一個帶箭頭View的實現代碼:

ArrowView.h

#import <UIKit/UIKit.h>

@interface ArrowView : UIView

@end

ArrowView.m

#import "ArrowView.h"

@implementation ArrowView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/ - (instancetype)init{ self = [super init]; if (self) { self.backgroundColor = [UIColor whiteColor]; } return self; } - (instancetype)initWithFrame:(CGRect)frame{ self = [super initWithFrame:frame]; if (self) { self.backgroundColor = [UIColor whiteColor]; }
return self; } - (void)drawRect:(CGRect)rect{ [super drawRect:rect]; NSLog(@"正在drawRect..."); //獲取當前圖形,視圖推入堆棧的圖形,相當於你所要繪制圖形的圖紙 CGContextRef ctx = UIGraphicsGetCurrentContext(); // [[UIColor whiteColor] set]; //創建一個新的空圖形路徑 CGContextBeginPath(ctx); NSLog(
@"開始繪制..."); //起始位置坐標 CGFloat origin_x = rect.origin.x; CGFloat origin_y = 10; //frame.origin.y + 10; //第一條線的位置坐標 CGFloat line_1_x = rect.size.width - 20; CGFloat line_1_y = origin_y; //第二條線的位置坐標 CGFloat line_2_x = line_1_x + 5; CGFloat line_2_y = rect.origin.y; //第三條線的位置坐標 CGFloat line_3_x = line_2_x + 5; CGFloat line_3_y = line_1_y; //第四條線的位置坐標 CGFloat line_4_x = rect.size.width; CGFloat line_4_y = line_1_y; //第五條線的位置坐標 CGFloat line_5_x = rect.size.width; CGFloat line_5_y = rect.size.height; //第六條線的位置坐標 CGFloat line_6_x = origin_x; CGFloat line_6_y = rect.size.height; CGContextMoveToPoint(ctx, origin_x, origin_y); CGContextAddLineToPoint(ctx, line_1_x, line_1_y); CGContextAddLineToPoint(ctx, line_2_x, line_2_y); CGContextAddLineToPoint(ctx, line_3_x, line_3_y); CGContextAddLineToPoint(ctx, line_4_x, line_4_y); CGContextAddLineToPoint(ctx, line_5_x, line_5_y); CGContextAddLineToPoint(ctx, line_6_x, line_6_y); CGContextClosePath(ctx); //設置填充顏色 UIColor *customColor = [UIColor colorWithWhite:0 alpha:0.8]; CGContextSetFillColorWithColor(ctx, customColor.CGColor); CGContextFillPath(ctx); } @end

然後在ViewController中調用,查看結果

ViewController.m

#import "ViewController.h"
#import "ArrowView.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    NSLog(@"begin...");
    
    ArrowView *view = [[ArrowView alloc] initWithFrame:CGRectMake(100, 100, 200, 80)];
    //[view setBackgroundColor:[UIColor orangeColor]];
    [self.view addSubview:view];
    
    NSLog(@"end...");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

結果截圖:

技術分享

控制臺打印結果:

技術分享

控制臺打印的線程ID是相同的,說明drawRect的方法是在主線程調用的。

iOS重寫drawRect方法實現帶箭頭的View