IOS实现圆形图片效果的两种方法

2020-01-15 17:54:59丽君

If you specify a value of 0.0, the scale factor is set to the scale factor of the device's main screen

4、代码:


CGContextRef context = UIGraphicsGetCurrentContext();

既然要使用上下文来绘制图片, 当然得获取当前的上下文对象了

5、代码:


[borderColor set];

先来看一下这个set的头文件注释


// Sets the fill and stroke colors in the current drawing context

给当前的上下文设置填充和描边的颜色, 说起填充色有没有想到画图软件中的填充 ?使用过PS的朋友应该很清楚.说白了这行代码的意思就是设置好颜色, 待会给圆环上色用...

6、代码:


CGFloat bigRadius = imageW * 0.5;
CGFloat centerX = bigRadius;
CGFloat centerY = bigRadius;
CGContextAddArc(context, centerX, centerY, bigRadius, 0, M_PI * 2, 0);

正常来讲画一个圆需要什么 ? 需要半径和圆心对不对

bigRadius 是带边框图片整体的绘制半径, 画圆需要半径, 这个就是!

centerX centerY 是圆心坐标的x和y

CGContextAddArc 这个方法表示给当前的上下文画一个圆弧, 我们来看下头文件的方法声明


void CGContextAddArc(CGContextRef cg_nullable c, CGFloat x, CGFloat y, CGFloat radius, CGFloat startAngle, CGFloat endAngle, int clockwise)

参数比较多, 我分别列出来其表示的意义:

     @param c 上下文

     @param x 圆弧中心点的x

     @param y 圆弧中心点的y

     @param radius 圆弧的半径(bigRadius)

     @param startAngle 起始点的角度

     @param endAngle 结束点的角度 M_PI * 2表示一周

     @param clockwise 顺时针画圆弧填1 逆时针填0

7、代码:


CGContextFillPath(context);

填充当前上下文, 用什么填充 ? 当然是填充色! 到这里我们得到了一个半径为bigRadius, 颜色为填充色的圆形上下文

8、代码:


CGFloat smallRadius = bigRadius - borderWidth;
CGContextAddArc(context, centerX, centerY, smallRadius, 0, M_PI * 2, 0);

意义和 -代码6- 一样, 给当前的上下文(一个有颜色的圆)添加一个圆弧, 其中的smallRadius就是中间图片的半径

9、代码:


CGContextClip(context);

头文件是这么说的: Intersect the context's path with the current clip path and use the
resulting path as the clip path for subsequent rendering operations.

大意是将当前的上下文以当前的剪辑路径(代码8所画的圆弧)进行剪辑, 然后使用剪辑后的路径(代码8得到的圆弧)来进行后续的着色操作.