Tuesday, December 3, 2013

How to crop an image with the Starling Framework?

So this is the post of how to perform image cropping on run-time in Starling Framework (AS3).

Allow me to grab any random image from the web for demo purposes, as below:

Question: how to crop the car image above? (Its original size is 300px width, 150px height). The final result is only the center car image.

The action is similar to cropping it with Microsoft Office Picture Manager, as shown below:

But how is it done in AS3 code?

First, let's have a look at the important function setTextCoords stated here.
Sets the texture coordinates of a vertex. Coordinates are in the range [0, 1].

To put the explanation of the function in a clearer picture:

Here, the vertex ID (first parameter) of a picture starts from top left, which is 0.
vertex ID 1 - Top right
vertex ID 2 - Bottom left
vertex ID 3 - Bottom right

Then, the coordinates (second parameter) simply means at which point of the image should the vertex be located. The allowed coordinates are in the range of [0,1]

So, let's see how we want to crop the image. As we can see above (the picture of Microsoft Office Picture Manager), i crop the image with the following criteria:
a) Left: 50px
b) Right: 50px
c) Top: 35px
d) Bottom: 10px

By converting them into the proper value (from 0 to 1), now we have:
a) Vertex 0th: (50/300, 35/150)
    - coordinates (1/6, 7/30)
b) Vertex 1st: ((300-50)/300, 35/150)
    - coordinates (5/6, 7/30)
c) Vertex 2nd: (50/300, (150-10)/150)
    - coordinates (1/6, 14/15)
d) Vertex 3rd: ((300-50)/300, (150-10)/150)
    - coordinates (5/6, 14/15)

Hence to crop the image with AS3, we just need the few lines below:

var bitmap:Bitmap = new car(); //assume you have embedded the car image
var myTexture:Texture = Texture.fromBitmap(bitmap);
var img:Image = new Image(myTexture);
img.setTexCoords(0, new Point(1/6, 7/30));
img.setTexCoords(1, new Point(5/6, 7/30));
img.setTexCoords(2, new Point(1/6, 14/15));
img.setTexCoords(3, new Point(5/6, 14/15));

Isn't that easy? At last, remember to set the width and height of your final image. Else, the cropped image will have the size similar to the original one (which would be undesirable).

No comments:

Post a Comment