IOS开发(98)之非XIB文件的自定义视图

1 前言

上一节我们谈到用XIB文件构建的自定义视图,今天我们来介绍一下,不借助XIB文件的自定义视图,共同学习一下。

2 详述

目录结构


这次我们不建立XIB文件,而是直接的Objective-C文件来代替XIB文件。

ZYCustomView.m:

- (void)drawRect:(CGRect)rect
{
    CGRect bounds = [self bounds];
    CGPoint center;
    center.x = bounds.origin.x + bounds.size.width / 2.0;
    center.y = bounds.origin.y + bounds.size.height / 2.0;
    //创建图形路径句柄
    CGMutablePathRef path = CGPathCreateMutable();
    //设置矩形的边界
    CGRect rectangle = CGRectMake(center.x-100, center.y-150,200.0f, 300.0f);
    //添加矩形到路径中
    CGPathAddRect(path,NULL, rectangle);
    //获得上下文句柄
    CGContextRef currentContext = UIGraphicsGetCurrentContext();
    //添加路径到上下文中
    CGContextAddPath(currentContext, path);
    //填充颜色
    [[UIColor colorWithRed:0.20f green:0.60f blue:0.80f alpha:1.0f] setFill];
    //设置画笔颜色
    [[UIColor brownColor] setStroke];
    //设置边框线条宽度
    CGContextSetLineWidth(currentContext,5.0f);
    //画图
    CGContextDrawPath(currentContext, kCGPathFillStroke);
    /* 释放路径 */
    CGPathRelease(path);
    
    // 创建一个字符串
    NSString *text = @"我是Developer_Zhang";
    
    UIFont *font = [UIFont boldSystemFontOfSize:20];
    // 设置Rect
    CGRect textRect;
    textRect.size = [text sizeWithFont:font];
    textRect.origin.x = center.x - textRect.size.width / 2.0;
    textRect.origin.y = center.y - textRect.size.height / 2.0;
    // 设置字体颜色
    [[UIColor redColor] setFill];
    //设置阴影
    CGSize offset = CGSizeMake(4, 3);
    //阴影颜色为黑色
    CGColorRef color = [[UIColor blackColor] CGColor];
    //模糊半径为2.0
    CGContextSetShadowWithColor(currentContext, offset, 2.0, color);
    [text drawInRect:textRect
            withFont:font];
}

ZYViewController.m:

- (void)viewDidLoad
{
    [super viewDidLoad];
    //创建一个窗体大小的CGRect
    CGRect wholeWindow = [[self.view window] bounds];
    // 创建一个窗体大小的HypnosisView实例
    self.view = [[ZYCustomView alloc] initWithFrame:wholeWindow];
    [self.view setBackgroundColor:[UIColor whiteColor]];
}

运行结果:


3 结语

以上是所有内容,希望对大家有所帮助。

Demo代码下载:http://download.csdn.net/detail/u010013695/5420485

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值