The canvas is an incredible widget, with more fascinating features than most people are aware of. However, it does have some limitations, and an easy method for "zooming" the view without actually scaling all the objects is one of them. (The ability to rotate objects is another big missing feature.)
The strategy you came up with is the standard method of emulating a "zoom" feature. Keep in mind that one limitation of this approach is that the canvas's
scale operation basically scales object coordinates. It doesn't scale other object attributes, such as width or the font size of text objects. It also doesn't scale bitmaps or embedded images.
Here's a simple procedure called
zoom that might help to get you started. Not only does it scale all of the objects on a canvas by a given scaling factor, but it also resizes font size for text objects:
Code:
proc zoom {canvas scale} {
$canvas scale all 0 0 $scale $scale
foreach item [$canvas find all] {
if {[$canvas type $item] == "text"} {
set font [font actual [$canvas itemcget $item -font]]
set index [lsearch -exact $font -size]
incr index
set size [lindex $font $index]
set size [expr {round($size * $scale)}]
set font [lreplace $font $index $index $size]
$canvas itemconfigure $item -font $font
}
}
$canvas configure -scrollregion [$canvas bbox all]
}
Note the use of the
font actual command in there. It returns a full font specification of the font given as an argument. You need because if you use a "short form" font specification like "helvetica 16 bold", that's exactly what you'd get back when you queried the item's font value. I need the full specification so that I can search for the "-size".
Also note that when computing the new font size, I had to round it to the nearest integer value. Tcl doesn't support fractional font sizes.
A better approach would be to create named font "styles" with the
font create command and use these named styles for all text that you place on the canvas. Then, when you want to scale the font size, just modify the definitions of the font styles and those chages are automatically applied to all text using those styles. For example:
Code:
font create title -family gillsans -size 14 -weight bold
font create body -family {Lucida Sans} -size 10
canvas .c
pack .c
.c create text 50 50 -anchor nw -text "Avia Training" -font title
.c create text 50 100 -anchor nw -text "and Consulting" -font body
# Later on, when you want to scale the size
set size [font configure title -size]
set size [expr {round($size * 0.8)}]
font configure title -size $size
set size [font configure body -size]
set size [expr {round($size * 0.8)}]
font configure body -size $size
- Ken Jones, President, ken@avia-training.com
Avia Training and Consulting,
866-TCL-HELP (866-825-4357) US Toll free
415-643-8692 Voice
415-643-8697 Fax