mercredi 19 avril 2017

How to rotate an image

How to rotate an image

Basically, rotate an image in not obvious since we have to recalculate the coordinates of each pixel according to the required rotation and interpolate values in order to avoid aliasing effects of the image. Fortunately, Red draw dialect offers a efficient solution with the command rotate which sets the clockwise rotation about a given point, in degrees. If optional center is not supplied, the rotate is about the origin of the current user coordinate system. Negative numbers can be used for counter-clockwise rotation.  

Draw block composition

In the following example, we just define a block of draw commands such as drawBlk: compose [scale (sFactor) (sFactor) translate (transl) rotate (rot) (centerXY) image img]

We use compose which returns  a copy of the block and  evaluates values in brackets. 

Before the image rotation, we reduce a little bit the size of the image in x and y with scale command  and we translate the image  in the window in order that rotation remains inside the image container. After it is really easy to update the block element (here drawBlk/7) containing the value of rotation provided by the slider. 


Red is fantastic!

Code example


Red [
    Title:   "Rotate image"
    Author:  "Francois Jouen"
    File:    %rotateImage.red
    Needs:   'View
]

margins: 10x10
; use the image you want
img: load %lena.jpg
iSize: img/size
centerXY: img/size / 2
rot: 0.0
transl:  144x144 ; or 96x96  for windows version
sFactor: 0.625
drawBlk: compose [scale (sFactor) (sFactor) translate (transl) rotate (rot) (centerXY) image img]


; ***************** Test Program ****************************
view win: layout [
        title "Rotate Image"
        origin margins space margins
        sl1: slider 310     [sz/text: form to integer! face/data * 360 
                             rot: face/data * 360.0 drawBlk/7: rot]
        sz: field 35 "0"
        text "Degrees"
        button 55 "Quit"    [Quit]
        return 
        canvas: base iSize white draw drawBlk   
        do [ sl1/data: 0.0 ]
]

Result




Aucun commentaire:

Enregistrer un commentaire