Android拆分Bitmap完整示例

MainActivity如下:

package cc.testsplitimage;
import java.util.ArrayList;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
/**
 * Demo描述:
 * 拆分图片
 * 
 * 参考资料:
 * http://blog.csdn.net/arui319/article/details/7470193
 * Thank you very much
 */
public class MainActivity extends Activity {
    private Button mSplitButton;
    private Bitmap mRawBitmap;
    private ImageView mImageView;
    private int row;
    private int column;
    private ArrayList mPartImagesArrayLis;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		init();
	}
	
    private void init(){
    	mSplitButton=(Button) findViewById(R.id.splitButton);
    	mSplitButton.setOnClickListener(new ClickListenerImpl());
    	mImageView=(ImageView) findViewById(R.id.imageView);
    	mRawBitmap=BitmapFactory.decodeResource(getResources(), R.drawable.e);
    	row=3;
    	column=3;
    }
    
    private class ClickListenerImpl implements OnClickListener{
		@Override
		public void onClick(View view) {
			switch (view.getId()) {
			case R.id.splitButton:
				mPartImagesArrayLis=splitImage(mRawBitmap, row, column);
				mImageView.setImageBitmap(null);
				break;
			default:
				break;
			}
		}
    }
    /**
     * @param rawBitmap 原来的Bitmap
     * @param row       切成几行
     * @param column    切成几列
     * @return
     */
    private ArrayList splitImage(Bitmap rawBitmap,int row,int column){
    	ArrayList partImagesArrayList=new ArrayList(row*column);
    	int rawBitmapWidth=rawBitmap.getWidth();
    	int rawBitmapHeight=rawBitmap.getHeight();
    	System.out.println("rawBitmapWidth="+rawBitmapWidth+",rawBitmapHeight="+rawBitmapHeight);
    	int perPartWidth=rawBitmapWidth/column;
    	int perPartHeight=rawBitmapHeight/row;
    	System.out.println("perPartWidth="+perPartWidth+",perPartHeight="+perPartHeight);
    	Bitmap perBitmap=null;
    	for (int i = 0; i < row; i++) {
			for (int j = 0; j < column; j++) {
				int x=j*perPartWidth;
				int y=i*perPartHeight;
				System.out.println("i="+i+",j="+j+",x="+x+",y="+y);
				perBitmap=Bitmap.createBitmap(rawBitmap, x, y, perPartWidth, perPartHeight);
				partImagesArrayList.add(perBitmap);
			}
		}
    	System.out.println("size="+partImagesArrayList.size());
		return partImagesArrayList;
    }
   
}


 

main.xml如下:



    


 

你可能感兴趣的:(Android核心)