IOS 自定义控件之写文字和画图片

来源:互联网 发布:程序员和产品经理gif 编辑:程序博客网 时间:2024/04/27 21:57

1 新建一个类,集成自UIView

2 重写drawRect:方法

- (void)drawRect:(CGRect)rect {        //获取矩形的宽高    CGFloat w = rect.size.width;    CGFloat h = rect.size.height;       //画图片    UIImage *image = [UIImage imageNamed:@"yourimagename"];    //以某一点为原点,以图片原尺寸画出图片    //image drawAtPoint:CGPointZero];            //指定图片的位置,大小,放大或缩小将图片画在相应位置    //[image drawInRect:CGRectMake(10, 10, 100, 100)];           //平铺的方式画图片    [image drawAsPatternInRect:CGRectMake(0, 0, 150, 150)];            // Drawing code    //画文字    NSString *text = @"我们是共产主义接班人,继承革命先辈的光荣传统!";    //这个方法不会换行    //[text drawAtPoint:CGPointMake(10, 100) withAttributes:nil];        // 设置字体的样式    NSDictionary *attr = @{NSFontAttributeName:[UIFont systemFontOfSize:13],NSForegroundColorAttributeName:[UIColor redColor]};        //指定宽度和高度    [text drawInRect:CGRectMake(0, 0, w, h) withAttributes:attr];}


3 打开storyboard,拖一个UIView放进去,将Class改成之前新建的类,运行,查看效果。

0 0