天天看點

iOS中自定義繪圖的兩種實作方式

iOS中自定義繪圖的兩種實作方式

在日常打應用中,有的時候我們需要自己在UIView中自定義繪制一些線條來達到應用打效果,首先我們想到打就是在UIView中打- (void)drawRect:(CGRect)rect方法中進行線條的繪制。

不錯,我們是可以這麼搞,而且這麼搞也比較打不錯,但是唯一令人煩心就是在這個方法中寫打繪制方法,都是openGL原生态的方法(也就是c語言的文法),一會兒oc,一會兒c是有點兒暈乎乎的,是以今天将介紹另外的一個oc的寫法,當然了,第一種drawRect方法中打方法也是會介紹一下的。

第一種方法:在UIView中的- (void)drawRect:(CGRect)rect中繪制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
      
- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetLineWidth(context, 1.0f);
    CGContextSetAllowsAntialiasing(context, false);
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);

    CGContextMoveToPoint(context, 50.0f, 0.0f);
    CGContextAddLineToPoint(context, 50.0f, 100.0f);
    CGContextMoveToPoint(context, 0.0f, 50.0f);
    CGContextAddLineToPoint(context, 100.0f, 50.0f);

    CGContextStrokePath(context);
}

           

通過上述的代碼就在UIViews上面畫了一個

十字架

了。

第二種方法:運用CAShapeLayer類添加到UIView的layer上面進行繪制

TestView.h

1
2
3
4
5
      
#import <Foundation/Foundation.h>

@interface TestView : UIView

@end

           

TestView.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
      
#import "TestView.h"

@implementation TestView {
    CAShapeLayer *shapeLayer;
}

- (instancetype)init {
    if ((self = [super init])) {

        shapeLayer = [CAShapeLayer layer];
        shapeLayer.lineWidth = 1.0f;
        shapeLayer.fillColor = [UIColor clearColor].CGColor;
        shapeLayer.lineJoin = kCALineCapSquare;
        shapeLayer.strokeColor = [UIColor redColor].CGColor;
        shapeLayer.strokeEnd = 10.0f;

        self.layer.masksToBounds = NO;
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];

    [self.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)];

    shapeLayer.frame = CGRectMake(0.0f, 0.0f, self.layer.frame.size.width, self.layer.frame.size.height);

    UIBezierPath *bezierPath = [UIBezierPath bezierPath];
    [bezierPath moveToPoint:CGPointMake(self.frame.size.width/2, 0.0f)];
    [bezierPath addLineToPoint:CGPointMake(self.frame.size.width/2, self.frame.size.height)];
    [bezierPath moveToPoint:CGPointMake(0.0f, self.frame.size.height/2)];
    [bezierPath addLineToPoint:CGPointMake(self.frame.size.width, self.frame.size.height/2)];

    shapeLayer.path = bezierPath.CGPath;
    [self.layer addSublayer:shapeLayer];
}

@end

           

上述效果和第一種方法一樣,都是在UIView上面畫了一個

十字架

Posted by kingiol 2013-10-16 Wed  iOS