PyCairo – Setting Context Color
Last Updated :
18 Feb, 2022
In this article, we will see how we can set context colors in pycairo Python. Pycairo is a Python module providing bindings for the Cairo graphics library. This library is used for creating SVG i.e vector files in python. The easiest and quickest way to open an SVG file to view it (read only) is with a modern web browser like Chrome, Firefox, Edge, or Internet Explorer—nearly all of them should provide some sort of rendering support for the SVG format. Color can be set using RGBA model, RGBA stands for red green blue alpha. While it is sometimes described as a color space, it is actually the three-channel RGB color model supplemented with a fourth alpha channel.
In order to this we will use set_source_rgba method with the Context object
Syntax: context.set_source_rgba(0, 0, 0, 1)
Argument: It takes color format in RGBA model
Return: It returns None
Example 1 :
Python
import cairo
with cairo.SVGSurface( "geek007.svg" , 700 , 700 ) as surface:
context = cairo.Context(surface)
context.set_source_rgba( 0 , 0 , 0 , 1 )
context.set_line_width( 4 )
context.move_to( 40 , 30 )
context.rectangle( 100 , 100 , 100 , 100 )
context.stroke()
print ( "File Saved" )
|
Setting color of the context
context.set_source_rgba (0, 0, 0, 1)
Output :
Example 2 :
Python3
import cairo
with cairo.SVGSurface( "geek007.svg" , 700 , 700 ) as surface:
context = cairo.Context(surface)
context.set_source_rgba( 4 , 0 , 4 , 0.5 )
context.set_line_width( 40 )
context.move_to( 40 , 30 )
context.rectangle( 100 , 100 , 100 , 100 )
context.stroke()
print ( "File Saved" )
|
Setting color of the context
context.set_source_rgba (4, 0, 4, 0.5)
Output :
Example 3 :
Python3
import cairo
with cairo.SVGSurface( "geek007.svg" , 700 , 700 ) as surface:
context = cairo.Context(surface)
context.set_source_rgba( 180 , 150 , 0 , 0.5 )
context.set_line_width( 40 )
context.move_to( 40 , 30 )
context.rectangle( 100 , 100 , 100 , 100 )
context.stroke()
print ( "File Saved" )
|
Setting color of the context
context.set_source_rgba (180, 150, 0, 0.5)
Output :
Share your thoughts in the comments
Please Login to comment...