自己画View其实没那么可怕

论坛 期权论坛 脚本     
匿名技术用户   2020-12-23 01:25   151   0

身边好多 刚入行的朋友 特别恐惧 自己画 控件 其实 这个东西 并不是太难 (主要归功于苹果的工程师们 , 因为OC最接近自然语言) , 现在 我们就 画一个渐变色的VIew (我就用一些特别low的 方式 一步步 说一说过程, <=.= 网上一查 一大把嘿嘿>)



- (void)creatGround {

//创建CGContextRef

//这句话 可以理解为 创建一张画布 字面上看着 就是说 开始绘制 上下文 括号里的就是 画布的大小啦

UIGraphicsBeginImageContext(self.bounds.size);

//重绘图像

CGContextRef gc = UIGraphicsGetCurrentContext();

//创建CGMutablePathRef就是 绘画的路径 可以当成 铅笔的走向 这里设定的是 可变的 也就是 可以动的

CGMutablePathRef path =CGPathCreateMutable();

//绘制Path(这里就是 点到点的 走向啦 点动成线 线动成面 完美的诠释了这句话 )

// 设置 范围 (就是你的铅笔可以瞎几把画的范围, 这里是父视图的全范围)

CGRect rect =CGRectMake(0,0, self.frame.size.width,self.frame.size.height);

//不要被MoveToPoint 的只管翻译意思蒙蔽了, 这个其实就 起点

CGPathMoveToPoint(path,NULL, CGRectGetMinX(rect),0);

//(特别注意 OC 画图 是逆时针走向的 比如 口 先画竖线 再画 横 在往上 再往左)

CGPathAddLineToPoint(path,NULL, 0,CGRectGetMaxY(rect));

// CGPathAddLineToPoint 里面的参数 就不说了 试着去改一改 看看效果就知道了

CGPathAddLineToPoint(path,NULL, CGRectGetWidth(rect),CGRectGetMaxY(rect));

CGPathAddLineToPoint(path,NULL, CGRectGetWidth(rect),0);

//结束 回归起点 (就是闭合 从最后的Point 链接到原点 )

CGPathCloseSubpath(path);

//绘制渐变

[selfdrawLinearGradient:gcpath:path startColor:UWPink.CGColorendColor:[UIColorhx_colorWithHexRGBAString:@"#f54f68"].CGColor];

//注意释放CGMutablePathRef

CGPathRelease(path);

//Context中获取图像,并显示在界面上

UIImage *img = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

UIImageView *imgView = [[UIImageViewalloc] initWithImage:img];

[selfaddSubview:imgView];

}








- (void)drawLinearGradient:(CGContextRef)context

path:(CGPathRef)path

startColor:(CGColorRef)startColor

endColor:(CGColorRef)endColor

{

CGColorSpaceRef colorSpace =CGColorSpaceCreateDeviceRGB();

CGFloat locations[] = {0.0,1.0 };

NSArray *colors =@[(__bridgeid) startColor, (__bridgeid) endColor];

CGGradientRef gradient =CGGradientCreateWithColors(colorSpace, (__bridgeCFArrayRef) colors, locations);

CGRect pathRect =CGPathGetBoundingBox(path);

//具体方向可根据需求修改

CGPoint startPoint =CGPointMake(CGRectGetMinX(pathRect),0);

CGPoint endPoint =CGPointMake(CGRectGetMinX(pathRect),CGRectGetMaxY(pathRect));

CGContextSaveGState(context);

CGContextAddPath(context, path);

CGContextClip(context);

CGContextDrawLinearGradient(context, gradient, startPoint, endPoint,0);

CGContextRestoreGState(context);

CGGradientRelease(gradient);

CGColorSpaceRelease(colorSpace);

}

/*复制粘贴 拿起键盘就是干*/


---------------------------没法再丑的博客------------------


分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP