拼图代码——两张图片拼接:
onCreate函数:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageview=(ImageView) findViewById(R.id.imageview);
Bitmap background=BitmapFactory.decodeResource(getResources(), R.drawable.back);
Bitmap foreground=BitmapFactory.decodeResource(getResources(), R.drawable.plane);
/*Canvas canvas=new Canvas(background);
drawImage(canvas, background, 0, foreground.getHeight(),
foreground.getWidth(), background.getHeight()/2, 0, 0);*/
Bitmap bitmap=toConformBitmap(background, foreground);
imageview.setImageBitmap(bitmap);
}拼接函数:
方法一:
<span style="font-size:18px;"> private Bitmap toConformBitmap(Bitmap background, Bitmap foreground){
if(background==null){
return null;
}
int bgWidth=background.getWidth();
int bgHeight=background.getHeight();
int fgWidth=foreground.getWidth();
int fgHeight=foreground.getHeight();
//创建一个新的和SRC长度宽度一样的位图
Bitmap newbmp=Bitmap.createBitmap(bgWidth+fgWidth, bgHeight+fgHeight, Config.ARGB_8888);
Canvas cv=new Canvas(newbmp);
cv.drawBitmap(background, 0, 0, null);//在0,0坐标开始画bg
cv.drawBitmap(foreground, 0, bgHeight, null);//在0,0坐标开始画fg,可以从任意位置画入
cv.save(Canvas.ALL_SAVE_FLAG);//保存
cv.restore();//存储
return newbmp;
}</span><span style="font-size:18px;"> private Bitmap toConformBitmap(Bitmap background, Bitmap foreground){
if(background==null){
<span style="white-space:pre"> </span>return null;
}
int bgWidth=background.getWidth();
int bgHeight=background.getHeight();
int fgWidth=foreground.getWidth();
int fgHeight=foreground.getHeight();
//创建一个新的和SRC长度宽度一样的位图
Bitmap newbmp=Bitmap.createBitmap(bgWidth+fgWidth, bgHeight+fgHeight, Config.ARGB_8888);
Canvas cv=new Canvas(newbmp);
//方法二
Rect dst=new Rect();
dst.left=0;
dst.top=0;
dst.right=bgWidth;
dst.bottom=bgHeight-50;
cv.drawBitmap(background, null, dst, null);
Rect dst2=new Rect();
dst2.left=0;
dst2.top=bgHeight;
double Xscale=bgWidth/fgWidth;//X轴缩放比例
dst2.bottom=(int) (bgHeight+fgHeight*Xscale);
dst2.right=bgWidth;
cv.drawBitmap(foreground, null, dst2, null);
dst2=null;
dst=null;
cv.save(Canvas.ALL_SAVE_FLAG);//保存
cv.restore();//存储
return newbmp;
}</span>保存函数:
//保存bitmap为一张图片
private String saveBitmap(Bitmap bitmap){
String imagePath=getApplication().getFilesDir().getAbsolutePath()+"/temp.jpg";
File file=new File(imagePath);
if(file.exists()){
file.delete();
}
try {
FileOutputStream out=new FileOutputStream(file);
if(bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)){
out.flush();
out.close();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(this, "保存失败", 1).show();
e.printStackTrace();
}
return imagePath;
}原文地址:http://blog.csdn.net/caiwencongwyj/article/details/45752311