Thứ Năm, 24 tháng 12, 2009

Zoom in / out and Move an Image in Android SDK

In this post: "how to zoom in /out and move an Image?". IFollow the step bellow you can create an application to load a picture show and zoom in/out an move:
  • Zoom in/out are used key_pad to control
  • Move is used tourchScreen to control
I created an class ViewExtend from View. In this class, we will load image to this view, zoom in/out and move.

Load an image:

image = context.getResources().getDrawable(R.drawable.abc);

This command is called in constructor of ViewExtend class. To use touch screen control , we will set setFocusableInTouchMode(true); (the parameter is true then we can use touch screen control and opposite)

To draw image to the view, we override the onDraw() function of View. In this function, We will set the size of image and any settings for image.
void onDraw(Canvas canvas){

image.setBounds(left, top, right, bottom);

...
// add more set here

....

image.draw(canvas);
}


Zoom in/out: We will use eventKeyDown to control this action.

public boolean onKeyDown(int keyCode, KeyEvent event){
mTouch = false;
if(keyCode == KeyEvent.KEYCODE_DPAD_UP)// zoom in
zoomControler += 10;
if(keyCode == KeyEvent.KEYCODE_DPAD_DOWN)// zoom out
zoomControler -= 10;
if(zoomControler<10)
zoomControler = 10;
invalidate();
return true;
}


If we don't change the setBounds image in onDraw() function, image will not zoom in / out. Example we can change this zoom like:
image.setBounds(x - zoomControler, y - zomControler, x + zoomControler, y + zoomControler);

Notes:
image is declared in this class.
x,y are the coordinate of root point that point is used to draw image.

Move control: Like zoom in/out control, we will change the position of image depend on which first position touch -> move and move up finger. In the first position touch, we will get the coordinate (x,y). For touch move and touch up, we also get coordinate (x1,y1). We can calculate the different position of (x,y) and (x1, y1) to set the image position in onDraw() function.




Không có nhận xét nào:

Cách dùng Markdown language

Theo Wikipedia: Markdown  là một ngôn ngữ đánh dấu với cú pháp văn bản thô  [5] , được thiết kế để có thể dễ dàng chuyển thành  HTML  và n...