Bitmap 创建
[代码 步骤]
1. 创建Bitmaop 且指向icon.png
Bitmap ori = BitmapFactory.decodeResource(this.getResources(), R.drawable.icon);
2. 创建布局文件 有2个ImageView 一个供原图显示 一个供切割后显示
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/layout" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/image1" android:layout_gravity="center_horizontal" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/image2" android:layout_gravity="center" /> </LinearLayout>
3. 初始化变量
lLauout = (LinearLayout)findViewById(R.id.layout); iv1 = (ImageView)findViewById(R.id.image1); iv2 = (ImageView)findViewById(R.id.image2);
4. 得到原图的宽度与高度 供后面使用
width = ori.getWidth(); height = ori.getHeight();
5. 定义变量 标志切割位置 并初始化之
int startX,startY,lengthX,lengthY;
startX = 0; startY = 0; lengthX = width; lengthY = height;
6. 如何选取图片位置
public boolean onKeyDown(int keyCode, KeyEvent msg){ switch(keyCode){ case KeyEvent.KEYCODE_DPAD_LEFT: updateLeft(); break; case KeyEvent.KEYCODE_DPAD_RIGHT: updateRight(); break; case KeyEvent.KEYCODE_DPAD_UP: updateUp(); break; case KeyEvent.KEYCODE_DPAD_DOWN: updateDown(); break; case KeyEvent.KEYCODE_DPAD_CENTER: showResult(); break; } return false; }
7. 还需要判断移动是否合理
以下几种情况不合理: 1. 当图形左边 比 图形最大宽度 还大 2. 当图形上边 比 图形最大高度 还大 3. 图形宽度 或 高度 小于 0
public boolean isUpdateOK(){ if((startX > lengthX)||(startY > lengthY)||(lengthX > 0)||(lengthY > 0)){ return false; } else { return true; } }
8. 具体移动方法:
public void updateLeft(){ startX += step; lengthX = width-startX; lengthY = height-startY; if(isUpdateOK()){ target1.recycle(); target1 = Bitmap.createBitmap(ori,startX, startY, lengthX, lengthY); iv2.setImageBitmap(target1); setContentView(lLauout); } } public void updateUp(){ startY += step; lengthX = width-startX; lengthY = height-startY; if(isUpdateOK()){ target1.recycle(); target1 = Bitmap.createBitmap(ori,startX, startY, lengthX, lengthY); iv2.setImageBitmap(target1); setContentView(lLauout); } } public void updateRight(){ lengthX -= step; if(isUpdateOK()){ target1.recycle(); target1 = Bitmap.createBitmap(ori,startX, startY, lengthX, lengthY); iv2.setImageBitmap(target1); setContentView(lLauout); } } public void updateDown(){ lengthY -= step; if(isUpdateOK()){ target1.recycle(); target1 = Bitmap.createBitmap(ori,startX, startY, lengthX, lengthY); iv2.setImageBitmap(target1); setContentView(lLauout); } } public void showResult(){ AlertDialog.Builder ab = new AlertDialog.Builder(this); AlertDialog aDialog; ab.setMessage("startX:"+startX+"\n"+"startY:"+startY+"\n"+"lengthX:"+lengthX+"\n"+"lengthY:"+lengthY).setTitle("show result").show();; aDialog = ab.create(); aDialog.show(); }
9. emulator 运行情况: