您的位置:首页 > 产品设计 > UI/UE

iOS绘图—— UIBezierPath 和 Core Graphics

2018-01-22 10:51 477 查看

一、drawRect方法什么时候触发

1.当view第一次显示到屏幕上时;
2.当调用view的setNeedsDisplay或者setNeedsDisplayInRect:方法时。

二、 六种绘图形式

至此,我们有了两大绘图框架的支持以及三种获得图形上下文的方法(drawRect:、drawRect: inContext:、UIGraphicsBeginImageContextWithOptions)。那么我们就有6种绘图的形式:

1 . 在UIView的子类方法drawRect:中绘制一个蓝色圆, 使用 UIKit方式:
1

2

3

4

5
override

func
drawRect(rect: CGRect)

{

       

let
p =
UIBezierPath(ovalInRect:

CGRectMake(0,

0,

100,

100))

       

UIColor.blueColor().setFill()

        p.fill()

}
2 . 在UIView的子类方法drawRect:中绘制一个蓝色圆, 使用 Core Graphics方式:
1

2

3

4

5

6
override

func
drawRect(rect: CGRect)

{

 

let
con =
UIGraphicsGetCurrentContext()!

      

CGContextAddEllipseInRect(con,

CGRectMake(0,

0,

100,

100))

       

CGContextSetFillColorWithColor(con,

UIColor.blueColor().CGColor)

 

CGContextFillPath(con)

}
3 . 在UIView子类的drawLayer:inContext:方法中,使用UIKit方式:
1

2

3

4

5

6

7
override

func
drawLayer(layer: CALayer, inContext ctx: CGContext)

{

   

UIGraphicsPushContext(ctx)

//将ctx设置为当前context

   

let
p =
UIBezierPath(ovalInRect:

CGRectMake(0,

0,

100,

100))

   

UIColor.blueColor().setFill()

    p.fill()

   

UIGraphicsPushContext(ctx)

}
4 . 在UIView子类的drawLayer:inContext:方法中,使用Core Graphics方式:
1

2

3

4

5
override

func
drawLayer(layer: CALayer, inContext ctx: CGContext)

{

       

CGContextAddEllipseInRect(ctx,

CGRectMake(0,

0,

100,

100))

       

CGContextSetFillColorWithColor(ctx,

UIColor.blueColor().CGColor)

 

CGContextFillPath(ctx)

}
5 . 使用UIGraphicsBeginImageContextWithOptions创建画板&用UIKit方式绘制:
1

2

3

4

5

6

7
UIGraphicsBeginImageContextWithOptions(CGSizeMake(100,

100), false,

0)

let

p =
UIBezierPath(ovalInRect:

CGRectMake(0,

0,

100,

100))

UIColor.blueColor().setFill()

p.fill()

let

image =
UIGraphicsGetImageFromCurrentImageContext()

UIGraphicsEndImageContext()

//to do something with the image
6 . 使用UIGraphicsBeginImageContextWithOptions创建画板&用Core
Graphics方式绘制:
1

2

3

4

5

6

7
UIGraphicsBeginImageContextWithOptions(CGSizeMake(100,

100), false,

0)

let

con =
UIGraphicsGetCurrentContext()

CGContextAddEllipseInRect(con,

CGRectMake(0,

0,

100,

100))

CGContextSetFillColorWithColor(con,

UIColor.redColor().CGColor)

CGContextFillPath(con)

let

image =
UIGraphicsGetImageFromCurrentImageContext()

UIGraphicsEndImageContext()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: