如何将自定义视图存储到Bitmap对象中

时间:2016-01-19 13:51:40

标签: android bitmap

如何将自定义视图存储到Bitmap对象中?例如,使用以下代码,我们可以将imageView对象存储到bitmap对象中。

Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();

但是如果我使用以下代码创建自定义视图,我如何将自定义视图存储到Bitmap对象中?

public class MainActivity extends Activity {
Custom custom;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//How Can I store the `custom` object into the `Bitmap` object? Can I do this? 

    }}

class Custom extends View{
    Paint paint;

    Custom(Context context){
super(context);
        paint = new Paint();
    }
    @Override
    protected void onDraw(Canvas canvas) {
//Some operations

    }

}

1 个答案:

答案 0 :(得分:0)

有一种方法可以做到这一点。你必须创建一个Bitmap和Canvas并调用view.draw(canvas);

这是代码:

public static Bitmap loadBitmapFromView(View v) { Bitmap b = Bitmap.createBitmap(v.getLayoutParams().width,v.getLayoutParams().height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b); v.layout(v.getLeft(), v.getTop(), v.getRight(), v.getBottom()); v.draw(c); return b; }