开发者

How can I "best fit" an arbitrary cairo (pycairo) path?

开发者 https://www.devze.com 2022-12-20 10:13 出处:网络
It seems like given the information in stroke_extents() and the translate(x, y) and scale(x, y) functions, I should be able to take any arbitrary cairo (I\'m using pycairo) path and \"best fit\" it. I

It seems like given the information in stroke_extents() and the translate(x, y) and scale(x, y) functions, I should be able to take any arbitrary cairo (I'm using pycairo) path and "best fit" it. In other words, center it and expand it to fill the available space.

Before drawing the path, I have scaled the canvas such that the origin is the lower left corner, up is y+, right is x+, and t开发者_高级运维he height and width are both 1. Given these conditions, this code seems to correctly scale the path:

# cr is the canvas
extents = cr.stroke_extents()
x_size = abs(extents[0]) + abs(extents[2])
y_size = abs(extents[1]) + abs(extents[3])
cr.scale(1.0 / x_size, 1.0 / y_size)

I cannot for the life of me figure out the translating though. Is there a simpler approach? How can I "best fit" a cairo path on its canvas?

Please ask for clarification if anything is unclear in this question.


I have found a solution that I like (at least for my purposes). Just create a new surface and paint the old surface on to the new one.


As for the scale only, I have done a similar thing to adjust an image inside a box with a "best-fit" approach. As about scale, here is the code:

available_width = 800
available_height = 600
path_width = 500    
figure_height = 700     

# formulas
width_ratio = float(available_width)/path_width
height_ratio = float(available_height)/figure_height
scale = min(height_ratio, width_ratio)

# result
new_path_width = path_width*scale
new_figure_height = figure_height*scale

print new_path_width, new_figure_height

The image gets drawn aligned to the origin (top left in my case), so perhaps a similar thing should be done to translate the path.

Also, this best fit is intended to preserve aspect ratio. If you want to stretch the figure, use each of the ratios instead of the 'scale' variable.

Hope I have helped

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号