ios自定义UIView

通常在我们在开发ios应用时,系统已经给我们提供了足够的UI组件供我们开发,比如UIView以及其子类UIButton,UILabel,UIScrollview等等,但有些时候系统的组件不能满足我们的需求,这时候需要自定义视图以满足需求,自定义视图需要继承已经具有某些特征的父类视图,本文通过继承UIView达到自定义视图的目的,来加深对自定义视图以及CoreGraphics.framework的理解,废话不多说,进入正题:

一.首先继承UIView,重写其- (void)drawRect:(CGRect)rect方法

二.画矩形:

//矩形大小
    CGRect rectFrame = CGRectMake(50, 50, 100, 100);
    //CGContextSetRGBStrokeColor(context,1.0f, 1.0f, 1.0f, 1.0f);//设置画笔颜色
    CGContextSetStrokeColorWithColor(context, [UIColor greenColor].CGColor);//设置画笔颜色
   // CGContextSetRGBFillColor(context, .4f, .2f, .1f, 1);//设置填充颜色
    CGContextSetFillColorWithColor(context, [UIColor orangeColor].CGColor);//设置填充颜色
    CGContextAddRect(context,rectFrame);
    //设置矩形范围
    CGContextDrawPath(context,kCGPathFillStroke);
三.在矩形上画简单文字

// 简单的画文字
    NSString *text = @"画文字画文字画文字画文字";
    UIFont *font = [UIFont boldSystemFontOfSize:14];
    // 设置需要画的矩形大小
    CGRect textRect;
    textRect.size = [text sizeWithFont:font];//根据字体大小设置文本区域的大小
    textRect.origin.x = rectFrame.origin.x;
    textRect.origin.y = rectFrame.origin.y;
    // 填充context颜色
    [[UIColor blackColor] setFill];
    //设置阴影的偏移量,向右便宜4,向下偏移3
    CGSize offset = CGSizeMake(4, 3);
    //设置阴影颜色
    CGColorRef color = [[UIColor darkGrayColor] CGColor];
    CGContextSetShadowWithColor(context, offset, 2.0, color);
    [text drawInRect:textRect
            withFont:font];

四.画有省略号的文字

text = @"画文字画文字画文字画文字";
    textRect.size  = CGSizeMake(100, 10);
    textRect.origin.x = rectFrame.origin.x;
    textRect.origin.y = rectFrame.origin.y+20;
    // Set the fill color of the current context to black
    [[UIColor blackColor] setFill];
    //画文字,在超出范围时显示省略号在末尾
    [text drawInRect:textRect withFont:font lineBreakMode:NSLineBreakByTruncatingTail];

五.让文字居中显示

//4.让文字居中显示
    text = @"画文字";
    textRect.size  = CGSizeMake(100, 10);
    textRect.origin.x = rectFrame.origin.x;
    textRect.origin.y = rectFrame.origin.y+40;
    // Set the fill color of the current context to black
    [[UIColor blackColor] setFill];
    //画文字,在超出范围时显示省略号在末尾,并居中显示
    [text drawInRect:textRect withFont:font lineBreakMode:NSLineBreakByTruncatingTail alignment:NSTextAlignmentCenter];
最终效果图如下:


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值