-
-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathcontext.py
2193 lines (1784 loc) · 80.9 KB
/
context.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding: utf8
"""
cairocffi.context
~~~~~~~~~~~~~~~~~
Bindings for Context objects.
:copyright: Copyright 2013 by Simon Sapin
:license: BSD, see LICENSE for details.
"""
from . import ffi, cairo, _check_status, constants
from .matrix import Matrix
from .patterns import Pattern
from .surfaces import Surface
from .fonts import FontFace, ScaledFont, FontOptions, _encode_string
from .compat import xrange
PATH_POINTS_PER_TYPE = {
constants.PATH_MOVE_TO: 1,
constants.PATH_LINE_TO: 1,
constants.PATH_CURVE_TO: 3,
constants.PATH_CLOSE_PATH: 0
}
def _encode_path(path_items):
"""Take an iterable of ``(path_operation, coordinates)`` tuples
in the same format as from :meth:`Context.copy_path`
and return a ``(path, data)`` tuple of cdata object.
The first cdata object is a ``cairo_path_t *`` pointer
that can be used as long as both objects live.
"""
points_per_type = PATH_POINTS_PER_TYPE
path_items = list(path_items)
length = 0
for path_type, coordinates in path_items:
num_points = points_per_type[path_type]
length += 1 + num_points # 1 header + N points
if len(coordinates) != 2 * num_points:
raise ValueError('Expected %d coordinates, got %d.' % (
2 * num_points, len(coordinates)))
data = ffi.new('cairo_path_data_t[]', length)
position = 0
for path_type, coordinates in path_items:
header = data[position].header
header.type = path_type
header.length = 1 + len(coordinates) // 2
position += 1
for i in xrange(0, len(coordinates), 2):
point = data[position].point
point.x = coordinates[i]
point.y = coordinates[i + 1]
position += 1
path = ffi.new('cairo_path_t *', (constants.STATUS_SUCCESS, data, length))
return path, data
def _iter_path(pointer):
"""Take a cairo_path_t * pointer
and yield ``(path_operation, coordinates)`` tuples.
See :meth:`Context.copy_path` for the data structure.
"""
_check_status(pointer.status)
data = pointer.data
num_data = pointer.num_data
points_per_type = PATH_POINTS_PER_TYPE
position = 0
while position < num_data:
path_data = data[position]
path_type = path_data.header.type
points = ()
for i in xrange(points_per_type[path_type]):
point = data[position + i + 1].point
points += (point.x, point.y)
yield (path_type, points)
position += path_data.header.length
class Context(object):
"""A :class:`Context` contains the current state of the rendering device,
including coordinates of yet to be drawn shapes.
Cairo contexts are central to cairo
and all drawing with cairo is always done to a :class:`Context` object.
:param target: The target :class:`Surface` object.
Cairo contexts can be used as Python :ref:`context managers <with>`.
See :meth:`save`.
"""
def __init__(self, target):
self._init_pointer(cairo.cairo_create(target._pointer))
def _init_pointer(self, pointer):
self._pointer = ffi.gc(pointer, cairo.cairo_destroy)
self._check_status()
def _check_status(self):
_check_status(cairo.cairo_status(self._pointer))
@classmethod
def _from_pointer(cls, pointer, incref):
"""Wrap an existing :c:type:`cairo_t *` cdata pointer.
:type incref: bool
:param incref:
Whether increase the :ref:`reference count <refcounting>` now.
:return:
A new :class:`Context` instance.
"""
if pointer == ffi.NULL:
raise ValueError('Null pointer')
if incref:
cairo.cairo_reference(pointer)
self = object.__new__(cls)
cls._init_pointer(self, pointer)
return self
def get_target(self):
"""Return this context’s target surface.
:returns:
An instance of :class:`Surface` or one of its sub-classes,
a new Python object referencing the existing cairo surface.
"""
return Surface._from_pointer(
cairo.cairo_get_target(self._pointer), incref=True)
##
## Save / restore
##
def save(self):
"""Makes a copy of the current state of this context
and saves it on an internal stack of saved states.
When :meth:`restore` is called,
the context will be restored to the saved state.
Multiple calls to :meth:`save` and :meth:`restore` can be nested;
each call to :meth:`restore` restores the state
from the matching paired :meth:`save`.
Instead of using :meth:`save` and :meth:`restore` directly,
it is recommended to use a :ref:`with statement <with>`::
with context:
do_something(context)
… which is equivalent to::
context.save()
try:
do_something(context)
finally:
context.restore()
"""
cairo.cairo_save(self._pointer)
self._check_status()
def restore(self):
"""Restores the context to the state saved
by a preceding call to :meth:`save`
and removes that state from the stack of saved states.
"""
cairo.cairo_restore(self._pointer)
self._check_status()
def __enter__(self):
self.save()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.restore()
##
## Groups
##
def push_group(self):
"""Temporarily redirects drawing to an intermediate surface
known as a group.
The redirection lasts until the group is completed
by a call to :meth:`pop_group` or :meth:`pop_group_to_source`.
These calls provide the result of any drawing
to the group as a pattern,
(either as an explicit object, or set as the source pattern).
This group functionality can be convenient
for performing intermediate compositing.
One common use of a group is to render objects
as opaque within the group, (so that they occlude each other),
and then blend the result with translucence onto the destination.
Groups can be nested arbitrarily deep
by making balanced calls to :meth:`push_group` / :meth:`pop_group`.
Each call pushes / pops the new target group onto / from a stack.
The :meth:`group` method calls :meth:`save`
so that any changes to the graphics state
will not be visible outside the group,
(the pop_group methods call :meth:`restore`).
By default the intermediate group will have
a content type of :obj:`COLOR_ALPHA <CONTENT_COLOR_ALPHA>`.
Other content types can be chosen for the group
by using :meth:`push_group_with_content` instead.
As an example,
here is how one might fill and stroke a path with translucence,
but without any portion of the fill being visible under the stroke::
context.push_group()
context.set_source(fill_pattern)
context.fill_preserve()
context.set_source(stroke_pattern)
context.stroke()
context.pop_group_to_source()
context.paint_with_alpha(alpha)
"""
cairo.cairo_push_group(self._pointer)
self._check_status()
def push_group_with_content(self, content):
"""Temporarily redirects drawing to an intermediate surface
known as a group.
The redirection lasts until the group is completed
by a call to :meth:`pop_group` or :meth:`pop_group_to_source`.
These calls provide the result of any drawing
to the group as a pattern,
(either as an explicit object, or set as the source pattern).
The group will have a content type of :obj:`content`.
The ability to control this content type
is the only distinction between this method and :meth:`push_group`
which you should see for a more detailed description
of group rendering.
:param content: A :ref:`CONTENT` string.
"""
cairo.cairo_push_group_with_content(self._pointer, content)
self._check_status()
def pop_group(self):
"""Terminates the redirection begun by a call to :meth:`push_group`
or :meth:`push_group_with_content`
and returns a new pattern containing the results
of all drawing operations performed to the group.
The :meth:`pop_group` method calls :meth:`restore`,
(balancing a call to :meth:`save` by the push_group method),
so that any changes to the graphics state
will not be visible outside the group.
:returns:
A newly created :class:`SurfacePattern`
containing the results of all drawing operations
performed to the group.
"""
return Pattern._from_pointer(
cairo.cairo_pop_group(self._pointer), incref=False)
def pop_group_to_source(self):
"""Terminates the redirection begun by a call to :meth:`push_group`
or :meth:`push_group_with_content`
and installs the resulting pattern
as the source pattern in the given cairo context.
The behavior of this method is equivalent to::
context.set_source(context.pop_group())
"""
cairo.cairo_pop_group_to_source(self._pointer)
self._check_status()
def get_group_target(self):
"""Returns the current destination surface for the context.
This is either the original target surface
as passed to :class:`Context`
or the target surface for the current group as started
by the most recent call to :meth:`push_group`
or :meth:`push_group_with_content`.
"""
return Surface._from_pointer(
cairo.cairo_get_group_target(self._pointer), incref=True)
##
## Sources
##
def set_source_rgba(self, red, green, blue, alpha=1):
"""Sets the source pattern within this context to a solid color.
This color will then be used for any subsequent drawing operation
until a new source pattern is set.
The color and alpha components are
floating point numbers in the range 0 to 1.
If the values passed in are outside that range, they will be clamped.
The default source pattern is opaque black,
(that is, it is equivalent to ``context.set_source_rgba(0, 0, 0)``).
:param red: Red component of the color.
:param green: Green component of the color.
:param blue: Blue component of the color.
:param alpha:
Alpha component of the color.
1 (the default) is opaque, 0 fully transparent.
:type red: float
:type green: float
:type blue: float
:type alpha: float
"""
cairo.cairo_set_source_rgba(self._pointer, red, green, blue, alpha)
self._check_status()
def set_source_rgb(self, red, green, blue):
"""Same as :meth:`set_source_rgba` with alpha always 1.
Exists for compatibility with pycairo.
"""
cairo.cairo_set_source_rgb(self._pointer, red, green, blue)
self._check_status()
def set_source_surface(self, surface, x=0, y=0):
"""This is a convenience method for creating a pattern from surface
and setting it as the source in this context with :meth:`set_source`.
The :obj:`x` and :obj:`y` parameters give the user-space coordinate
at which the surface origin should appear.
(The surface origin is its upper-left corner
before any transformation has been applied.)
The :obj:`x` and :obj:`y` parameters are negated
and then set as translation values in the pattern matrix.
Other than the initial translation pattern matrix, as described above,
all other pattern attributes, (such as its extend mode),
are set to the default values as in :class:`SurfacePattern`.
The resulting pattern can be queried with :meth:`get_source`
so that these attributes can be modified if desired,
(eg. to create a repeating pattern with :meth:`Pattern.set_extend`).
:param surface:
A :class:`Surface` to be used to set the source pattern.
:param x: User-space X coordinate for surface origin.
:param y: User-space Y coordinate for surface origin.
:type x: float
:type y: float
"""
cairo.cairo_set_source_surface(self._pointer, surface._pointer, x, y)
self._check_status()
def set_source(self, source):
"""Sets the source pattern within this context to :obj:`source`.
This pattern will then be used for any subsequent drawing operation
until a new source pattern is set.
.. note::
The pattern's transformation matrix will be locked
to the user space in effect at the time of :meth:`set_source`.
This means that further modifications
of the current transformation matrix
will not affect the source pattern.
See :meth:`Pattern.set_matrix`.
The default source pattern is opaque black,
(that is, it is equivalent to ``context.set_source_rgba(0, 0, 0)``).
:param source:
A :class:`Pattern` to be used
as the source for subsequent drawing operations.
"""
cairo.cairo_set_source(self._pointer, source._pointer)
self._check_status()
def get_source(self):
"""Return this context’s source.
:returns:
An instance of :class:`Pattern` or one of its sub-classes,
a new Python object referencing the existing cairo pattern.
"""
return Pattern._from_pointer(
cairo.cairo_get_source(self._pointer), incref=True)
##
## Context parameters
##
def set_antialias(self, antialias):
"""Set the :ref:`ANTIALIAS` of the rasterizer used for drawing shapes.
This value is a hint,
and a particular backend may or may not support a particular value.
At the current time,
no backend supports :obj:`SUBPIXEL <ANTIALIAS_SUBPIXEL>`
when drawing shapes.
Note that this option does not affect text rendering,
instead see :meth:`FontOptions.set_antialias`.
:param antialias: An :ref:`ANTIALIAS` string.
"""
cairo.cairo_set_antialias(self._pointer, antialias)
self._check_status()
def get_antialias(self):
"""Return the :ref:`ANTIALIAS` string."""
return cairo.cairo_get_antialias(self._pointer)
def set_dash(self, dashes, offset=0):
"""Sets the dash pattern to be used by :meth:`stroke`.
A dash pattern is specified by dashes, a list of positive values.
Each value provides the length of alternate "on" and "off"
portions of the stroke.
:obj:`offset` specifies an offset into the pattern
at which the stroke begins.
Each "on" segment will have caps applied
as if the segment were a separate sub-path.
In particular, it is valid to use an "on" length of 0
with :obj:`LINE_CAP_ROUND` or :obj:`LINE_CAP_SQUARE`
in order to distributed dots or squares along a path.
Note: The length values are in user-space units
as evaluated at the time of stroking.
This is not necessarily the same as the user space
at the time of :meth:`set_dash`.
If :obj:`dashes` is empty dashing is disabled.
If it is of length 1 a symmetric pattern is assumed
with alternating on and off portions of the size specified
by the single value.
:param dashes:
A list of floats specifying alternate lengths
of on and off stroke portions.
:type offset: float
:param offset:
An offset into the dash pattern at which the stroke should start.
:raises:
:exc:`CairoError`
if any value in dashes is negative,
or if all values are 0.
The context will be put into an error state.
"""
cairo.cairo_set_dash(
self._pointer, ffi.new('double[]', dashes), len(dashes), offset)
self._check_status()
def get_dash(self):
"""Return the current dash pattern.
:returns:
A ``(dashes, offset)`` tuple of a list and a float.
:obj:`dashes` is a list of floats,
empty if no dashing is in effect.
"""
dashes = ffi.new('double[]', cairo.cairo_get_dash_count(self._pointer))
offset = ffi.new('double *')
cairo.cairo_get_dash(self._pointer, dashes, offset)
self._check_status()
return list(dashes), offset[0]
def get_dash_count(self):
"""Same as ``len(context.get_dash()[0])``."""
# Not really useful with get_dash() returning a list,
# but retained for compatibility with pycairo.
return cairo.cairo_get_dash_count(self._pointer)
def set_fill_rule(self, fill_rule):
"""Set the current :ref:`FILL_RULE` within the cairo context.
The fill rule is used to determine which regions are inside
or outside a complex (potentially self-intersecting) path.
The current fill rule affects both :meth:`fill` and :meth:`clip`.
The default fill rule is :obj:`WINDING <FILL_RULE_WINDING>`.
:param fill_rule: A :ref:`FILL_RULE` string.
"""
cairo.cairo_set_fill_rule(self._pointer, fill_rule)
self._check_status()
def get_fill_rule(self):
"""Return the current :ref:`FILL_RULE` string."""
return cairo.cairo_get_fill_rule(self._pointer)
def set_line_cap(self, line_cap):
"""Set the current :ref:`LINE_CAP` within the cairo context.
As with the other stroke parameters,
the current line cap style is examined by
:meth:`stroke`, :meth:`stroke_extents`, and :meth:`stroke_to_path`,
but does not have any effect during path construction.
The default line cap is :obj:`BUTT <LINE_CAP_BUTT>`.
:param line_cap: A :ref:`LINE_CAP` string.
"""
cairo.cairo_set_line_cap(self._pointer, line_cap)
self._check_status()
def get_line_cap(self):
"""Return the current :ref:`LINE_CAP` string."""
return cairo.cairo_get_line_cap(self._pointer)
def set_line_join(self, line_join):
"""Set the current :ref:`LINE_JOIN` within the cairo context.
As with the other stroke parameters,
the current line cap style is examined by
:meth:`stroke`, :meth:`stroke_extents`, and :meth:`stroke_to_path`,
but does not have any effect during path construction.
The default line cap is :obj:`MITER <LINE_JOIN_MITER>`.
:param line_join: A :ref:`LINE_JOIN` string.
"""
cairo.cairo_set_line_join(self._pointer, line_join)
self._check_status()
def get_line_join(self):
"""Return the current :ref:`LINE_JOIN` string."""
return cairo.cairo_get_line_join(self._pointer)
def set_line_width(self, width):
"""Sets the current line width within the cairo context.
The line width value specifies the diameter of a pen
that is circular in user space,
(though device-space pen may be an ellipse in general
due to scaling / shear / rotation of the CTM).
.. note::
When the description above refers to user space and CTM
it refers to the user space and CTM in effect
at the time of the stroking operation,
not the user space and CTM in effect
at the time of the call to :meth:`set_line_width`.
The simplest usage makes both of these spaces identical.
That is, if there is no change to the CTM
between a call to :meth:`set_line_width`
and the stroking operation,
then one can just pass user-space values to :meth:`set_line_width`
and ignore this note.
As with the other stroke parameters,
the current line cap style is examined by
:meth:`stroke`, :meth:`stroke_extents`, and :meth:`stroke_to_path`,
but does not have any effect during path construction.
The default line width value is 2.0.
:type width: float
:param width: The new line width.
"""
cairo.cairo_set_line_width(self._pointer, width)
self._check_status()
def get_line_width(self):
"""Return the current line width as a float."""
return cairo.cairo_get_line_width(self._pointer)
def set_miter_limit(self, limit):
"""Sets the current miter limit within the cairo context.
If the current line join style is set to :obj:`MITER <LINE_JOIN_MITER>`
(see :meth:`set_line_join`),
the miter limit is used to determine
whether the lines should be joined with a bevel instead of a miter.
Cairo divides the length of the miter by the line width.
If the result is greater than the miter limit,
the style is converted to a bevel.
As with the other stroke parameters,
the current line cap style is examined by
:meth:`stroke`, :meth:`stroke_extents`, and :meth:`stroke_to_path`,
but does not have any effect during path construction.
The default miter limit value is 10.0,
which will convert joins with interior angles less than 11 degrees
to bevels instead of miters.
For reference,
a miter limit of 2.0 makes the miter cutoff at 60 degrees,
and a miter limit of 1.414 makes the cutoff at 90 degrees.
A miter limit for a desired angle can be computed as:
``miter_limit = 1. / sin(angle / 2.)``
:param limit: The miter limit to set.
:type limit: float
"""
cairo.cairo_set_miter_limit(self._pointer, limit)
self._check_status()
def get_miter_limit(self):
"""Return the current miter limit as a float."""
return cairo.cairo_get_miter_limit(self._pointer)
def set_operator(self, operator):
"""Set the current :ref:`OPERATOR`
to be used for all drawing operations.
The default operator is :obj:`OVER <OPERATOR_OVER>`.
:param operator: A :ref:`OPERATOR` string.
"""
cairo.cairo_set_operator(self._pointer, operator)
self._check_status()
def get_operator(self):
"""Return the current :ref:`OPERATOR` string."""
return cairo.cairo_get_operator(self._pointer)
def set_tolerance(self, tolerance):
"""Sets the tolerance used when converting paths into trapezoids.
Curved segments of the path will be subdivided
until the maximum deviation between the original path
and the polygonal approximation is less than tolerance.
The default value is 0.1.
A larger value will give better performance,
a smaller value, better appearance.
(Reducing the value from the default value of 0.1
is unlikely to improve appearance significantly.)
The accuracy of paths within Cairo is limited
by the precision of its internal arithmetic,
and the prescribed tolerance is restricted
to the smallest representable internal value.
:type tolerance: float
:param tolerance: The tolerance, in device units (typically pixels)
"""
cairo.cairo_set_tolerance(self._pointer, tolerance)
self._check_status()
def get_tolerance(self):
"""Return the current tolerance as a float."""
return cairo.cairo_get_tolerance(self._pointer)
##
## CTM: Current transformation matrix
##
def translate(self, tx, ty):
"""Modifies the current transformation matrix (CTM)
by translating the user-space origin by ``(tx, ty)``.
This offset is interpreted as a user-space coordinate
according to the CTM in place before the new call to :meth:`translate`.
In other words, the translation of the user-space origin takes place
after any existing transformation.
:param tx: Amount to translate in the X direction
:param ty: Amount to translate in the Y direction
:type tx: float
:type ty: float
"""
cairo.cairo_translate(self._pointer, tx, ty)
self._check_status()
def scale(self, sx, sy=None):
"""Modifies the current transformation matrix (CTM)
by scaling the X and Y user-space axes
by :obj:`sx` and :obj:`sy` respectively.
The scaling of the axes takes place after
any existing transformation of user space.
If :obj:`sy` is omitted, it is the same as :obj:`sx`
so that scaling preserves aspect ratios.
:param sx: Scale factor in the X direction.
:param sy: Scale factor in the Y direction.
:type sx: float
:type sy: float
"""
if sy is None:
sy = sx
cairo.cairo_scale(self._pointer, sx, sy)
self._check_status()
def rotate(self, radians):
"""Modifies the current transformation matrix (CTM)
by rotating the user-space axes by angle :obj:`radians`.
The rotation of the axes takes places
after any existing transformation of user space.
:type radians: float
:param radians:
Angle of rotation, in radians.
The direction of rotation is defined such that positive angles
rotate in the direction from the positive X axis
toward the positive Y axis.
With the default axis orientation of cairo,
positive angles rotate in a clockwise direction.
"""
cairo.cairo_rotate(self._pointer, radians)
self._check_status()
def transform(self, matrix):
"""Modifies the current transformation matrix (CTM)
by applying :obj:`matrix` as an additional transformation.
The new transformation of user space takes place
after any existing transformation.
:param matrix:
A transformation :class:`Matrix`
to be applied to the user-space axes.
"""
cairo.cairo_transform(self._pointer, matrix._pointer)
self._check_status()
def set_matrix(self, matrix):
"""Modifies the current transformation matrix (CTM)
by setting it equal to :obj:`matrix`.
:param matrix:
A transformation :class:`Matrix` from user space to device space.
"""
cairo.cairo_set_matrix(self._pointer, matrix._pointer)
self._check_status()
def get_matrix(self):
"""Return a copy of the current transformation matrix (CTM)."""
matrix = Matrix()
cairo.cairo_get_matrix(self._pointer, matrix._pointer)
self._check_status()
return matrix
def identity_matrix(self):
"""Resets the current transformation matrix (CTM)
by setting it equal to the identity matrix.
That is, the user-space and device-space axes will be aligned
and one user-space unit will transform to one device-space unit.
"""
cairo.cairo_identity_matrix(self._pointer)
self._check_status()
def user_to_device(self, x, y):
"""Transform a coordinate from user space to device space
by multiplying the given point
by the current transformation matrix (CTM).
:param x: X position.
:param y: Y position.
:type x: float
:type y: float
:returns: A ``(device_x, device_y)`` tuple of floats.
"""
xy = ffi.new('double[2]', [x, y])
cairo.cairo_user_to_device(self._pointer, xy + 0, xy + 1)
self._check_status()
return tuple(xy)
def user_to_device_distance(self, dx, dy):
"""Transform a distance vector from user space to device space.
This method is similar to :meth:`Context.user_to_device`
except that the translation components of the CTM
will be ignored when transforming ``(dx, dy)``.
:param dx: X component of a distance vector.
:param dy: Y component of a distance vector.
:type x: float
:type y: float
:returns: A ``(device_dx, device_dy)`` tuple of floats.
"""
xy = ffi.new('double[2]', [dx, dy])
cairo.cairo_user_to_device_distance(self._pointer, xy + 0, xy + 1)
self._check_status()
return tuple(xy)
def device_to_user(self, x, y):
"""Transform a coordinate from device space to user space
by multiplying the given point
by the inverse of the current transformation matrix (CTM).
:param x: X position.
:param y: Y position.
:type x: float
:type y: float
:returns: A ``(user_x, user_y)`` tuple of floats.
"""
xy = ffi.new('double[2]', [x, y])
cairo.cairo_device_to_user(self._pointer, xy + 0, xy + 1)
self._check_status()
return tuple(xy)
def device_to_user_distance(self, dx, dy):
"""Transform a distance vector from device space to user space.
This method is similar to :meth:`Context.device_to_user`
except that the translation components of the inverse CTM
will be ignored when transforming ``(dx, dy)``.
:param dx: X component of a distance vector.
:param dy: Y component of a distance vector.
:type x: float
:type y: float
:returns: A ``(user_dx, user_dy)`` tuple of floats.
"""
xy = ffi.new('double[2]', [dx, dy])
cairo.cairo_device_to_user_distance(self._pointer, xy + 0, xy + 1)
self._check_status()
return tuple(xy)
##
## Path
##
def has_current_point(self):
"""Returns whether a current point is defined on the current path.
See :meth:`get_current_point`.
"""
return bool(cairo.cairo_has_current_point(self._pointer))
def get_current_point(self):
"""Return the current point of the current path,
which is conceptually the final point reached by the path so far.
The current point is returned in the user-space coordinate system.
If there is no defined current point
or if the context is in an error status,
``(0, 0)`` is returned.
It is possible to check this in advance with :meth:`has_current_point`.
Most path construction methods alter the current point.
See the following for details on how they affect the current point:
:meth:`new_path`,
:meth:`new_sub_path`,
:meth:`append_path`,
:meth:`close_path`,
:meth:`move_to`,
:meth:`line_to`,
:meth:`curve_to`,
:meth:`rel_move_to`,
:meth:`rel_line_to`,
:meth:`rel_curve_to`,
:meth:`arc`,
:meth:`arc_negative`,
:meth:`rectangle`,
:meth:`text_path`,
:meth:`glyph_path`,
:meth:`stroke_to_path`.
Some methods use and alter the current point
but do not otherwise change current path:
:meth:`show_text`,
:meth:`show_glyphs`,
:meth:`show_text_glyphs`.
Some methods unset the current path and as a result, current point:
:meth:`fill`,
:meth:`stroke`.
:returns:
A ``(x, y)`` tuple of floats, the coordinates of the current point.
"""
# I’d prefer returning None if self.has_current_point() is False
# But keep (0, 0) for compat with pycairo.
xy = ffi.new('double[2]')
cairo.cairo_get_current_point(self._pointer, xy + 0, xy + 1)
self._check_status()
return tuple(xy)
def new_path(self):
""" Clears the current path.
After this call there will be no path and no current point.
"""
cairo.cairo_new_path(self._pointer)
self._check_status()
def new_sub_path(self):
"""Begin a new sub-path.
Note that the existing path is not affected.
After this call there will be no current point.
In many cases, this call is not needed
since new sub-paths are frequently started with :meth:`move_to`.
A call to :meth:`new_sub_path` is particularly useful
when beginning a new sub-path with one of the :meth:`arc` calls.
This makes things easier as it is no longer necessary
to manually compute the arc's initial coordinates
for a call to :meth:`move_to`.
"""
cairo.cairo_new_sub_path(self._pointer)
self._check_status()
def move_to(self, x, y):
"""Begin a new sub-path.
After this call the current point will be ``(x, y)``.
:param x: X position of the new point.
:param y: Y position of the new point.
:type float: x
:type float: y
"""
cairo.cairo_move_to(self._pointer, x, y)
self._check_status()
def rel_move_to(self, dx, dy):
"""Begin a new sub-path.
After this call the current point will be offset by ``(dx, dy)``.
Given a current point of ``(x, y)``,
``context.rel_move_to(dx, dy)`` is logically equivalent to
``context.move_to(x + dx, y + dy)``.
:param dx: The X offset.
:param dy: The Y offset.
:type float: dx
:type float: dy
:raises:
:exc:`CairoError` if there is no current point.
Doing so will cause leave the context in an error state.
"""
cairo.cairo_rel_move_to(self._pointer, dx, dy)
self._check_status()
def line_to(self, x, y):
"""Adds a line to the path from the current point
to position ``(x, y)`` in user-space coordinates.
After this call the current point will be ``(x, y)``.
If there is no current point before the call to :meth:`line_to`
this method will behave as ``context.move_to(x, y)``.
:param x: X coordinate of the end of the new line.
:param y: Y coordinate of the end of the new line.
:type float: x
:type float: y
"""
cairo.cairo_line_to(self._pointer, x, y)
self._check_status()
def rel_line_to(self, dx, dy):
""" Relative-coordinate version of :meth:`line_to`.
Adds a line to the path from the current point
to a point that is offset from the current point
by ``(dx, dy)`` in user space.
After this call the current point will be offset by ``(dx, dy)``.
Given a current point of ``(x, y)``,
``context.rel_line_to(dx, dy)`` is logically equivalent to
``context.line_to(x + dx, y + dy)``.
:param dx: The X offset to the end of the new line.
:param dy: The Y offset to the end of the new line.
:type float: dx
:type float: dy
:raises:
:exc:`CairoError` if there is no current point.
Doing so will cause leave the context in an error state.
"""
cairo.cairo_rel_line_to(self._pointer, dx, dy)
self._check_status()
def rectangle(self, x, y, width, height):