iOS中自定义绘图的两种实现方式

271 篇文章 0 订阅
65 篇文章 0 订阅

在日常打应用中,有的时候我们需要自己在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上面画了一个十字架

 2013-10-16 Wed  iOS

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值