PyCairo – Drawing different type of line caps
In this article, we will learn how we can draw different line caps types using PyCairo in python. The line caps are endpoints of lines.
Steps of Implementation :
- Import the Pycairo module.
- Create a SVG surface object and add context to it.
- Setting color of the context & line width
- Setting of line cap style using set_line_cap( )
- Creating a line.
There are three different types line cap styles in PyCairo.
1. set_line_cap ( cairo.LINE_CAP_BUTT )
Example :
Python3
import cairo
with cairo.SVGSurface( "geek94.svg" , 700 , 700 ) as surface:
context = cairo.Context(surface)
context.set_source_rgba( 0 , 0 , 0 , 1 )
context.set_line_width( 12 )
context.set_line_cap(cairo.LINE_CAP_BUTT)
context.move_to( 30 , 50 )
context.line_to( 150 , 50 )
context.stroke()
print ( "File Saved" )
|
Output :
2. set_line_cap ( cairo.LINE_CAP_ROUND )
Example :
Python3
import cairo
with cairo.SVGSurface( "geek94.svg" , 700 , 700 ) as surface:
context = cairo.Context(surface)
context.set_source_rgba( 0 , 0 , 0 , 1 )
context.set_line_width( 12 )
context.set_line_cap(cairo.LINE_CAP_ROUND)
context.move_to( 30 , 50 )
context.line_to( 150 , 50 )
context.stroke()
print ( "File Saved" )
|
Output :
3. set_line_cap ( cairo.LINE_CAP_SQUARE )
Example :
Python
import cairo
with cairo.SVGSurface( "geek94.svg" , 700 , 700 ) as surface:
context = cairo.Context(surface)
context.set_source_rgba( 0 , 0 , 0 , 1 )
context.set_line_width( 12 )
context.set_line_cap(cairo.LINE_CAP_SQUARE)
context.move_to( 30 , 50 )
context.line_to( 150 , 50 )
context.stroke()
print ( "File Saved" )
|
Output:
Note: A line with cairo.LINE_CAP_SQUARE cap used has a different size than a line with cairo.LINE_CAP_BUTT cap. If the line is z units wide, the line with cairo.LINE_CAP_SQUARE cap will be exactly z units greater in size; z/2 units at the beginning and z/2 units at the end.
All three type of line caps can be seen in the below python Example, and the output of each line cap can also be compared
Python3
import cairo
with cairo.SVGSurface( "geek94.svg" , 700 , 700 ) as surface:
context = cairo.Context(surface)
context.set_source_rgba( 0 , 0 , 0 , 1 )
context.set_line_width( 12 )
context.set_line_cap(cairo.LINE_CAP_SQUARE)
context.move_to( 30 , 50 )
context.line_to( 150 , 50 )
context.stroke()
context.set_line_cap(cairo.LINE_CAP_ROUND)
context.move_to( 30 , 90 )
context.line_to( 150 , 90 )
context.stroke()
context.set_line_cap(cairo.LINE_CAP_SQUARE)
context.move_to( 30 , 130 )
context.line_to( 150 , 130 )
context.stroke()
print ( "File Saved" )
|
Output :
Last Updated :
23 Jan, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...