将若干张图片拼接在一起形成一个全新的图片

Android 将若干张图片拼接在一起形成一个全新的图片

目的:使用Android技术将若干张图片拼接成为一张图片。

最开始的两张图如下所示:

拼接后的图片如下图所示:

这样就把两张图片拼接成为一张了。

拼接步骤:

  1.使用Bitmap创建一个空的Bitmap(内存区域)并定义这个bitmap的宽和高。对应的代码:

Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);

  2.实例化一个Canvas并将创建好的空的Bitmap放到画布中。对应代码:

Canvas canvas = new Canvas(bitmap);

  3.使用canvas将要拼接的图片绘制到这个空的bitmap中。对应代码:

canvas.drawBitmap(bit1, 0, 0, null);
canvas.drawBitmap(bit2, 0, bit1.getHeight(), null);

  4.返回组合后的Bitmap,并在View的onDraw方法中绘制,代码如下:

  @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawBitmap(bitmap, 0, 0, null);
        bitmap.recycle();
    }

下面贴出完整代码:

  1.JointBitmapView.java

复制代码

package cn.yw.lib.graphics;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.view.View;

/**
 * 将多张图片拼接在一起
 * @author yw-tony
 *
 */
public class JointBitmapView extends View{
    private Bitmap bitmap;
    public JointBitmapView(Context context,Bitmap bit1,Bitmap bit2) {
        super(context);
        bitmap = newBitmap(bit1,bit2);
    }
    /**
     * 拼接图片
     * @param bit1
     * @param bit2
     * @return 返回拼接后的Bitmap
     */
    private Bitmap newBitmap(Bitmap bit1,Bitmap bit2){
        
        int width = bit1.getWidth();
        int height = bit1.getHeight() + bit2.getHeight();
        //创建一个空的Bitmap(内存区域),宽度等于第一张图片的宽度,高度等于两张图片高度总和
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        //将bitmap放置到绘制区域,并将要拼接的图片绘制到指定内存区域
        Canvas canvas = new Canvas(bitmap);
        canvas.drawBitmap(bit1, 0, 0, null);
        canvas.drawBitmap(bit2, 0, bit1.getHeight(), null);
        return bitmap;
    }
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawBitmap(bitmap, 0, 0, null);
        bitmap.recycle();
    }

}

复制代码

2.JointBitmapActivity.java

复制代码

package cn.yw.lib.graphics;

import cn.yw.lib.R;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;

/**
 * 图片拼接
 * 
 * @author yw-tony
 * 
 */
public class JointBitmapActivity extends Activity {
    private JointBitmapView view;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /**
         * 这里使用BitmapFactory.decodeStream(InputStream is);方法加载图片可以有效的防止
         * 当内存过大时出现内存溢出的情况
         */
        Bitmap bit1 = BitmapFactory.decodeStream(getApplicationContext()
                .getResources().openRawResource(R.drawable.ic_launcher));
        Bitmap bit2 = BitmapFactory.decodeStream(getApplicationContext()
                .getResources().openRawResource(R.drawable.ic_launcher));
        view = new JointBitmapView(this, bit1, bit2);
        setContentView(view);

    }

}

复制代码

猜你喜欢

转载自blog.csdn.net/hk121/article/details/88100435
今日推荐