我有一个imageview,然后在此imageview上添加图像(标记)。 最后,我想创建一个位图,包括新标记。 但是,如果我尝试从相对布局创建一个位图,我创建一个没有新标记的图像!为什么呢?
imageview= (ImageView)findViewById(R.id.image);
//insert a marker on my imageview
final RelativeLayout rr = (RelativeLayout) findViewById(R.id.relative);
rr.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN){
int x = (int) event.getX() ;
int y = (int) event.getY();
RelativeLayout.LayoutParams lp =new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);; //Assuming you use a RelativeLayout
ImageView iv=new ImageView(getApplicationContext());
lp.setMargins(x,y,0,0);
iv.setLayoutParams(lp);
iv.setImageDrawable(getResources().getDrawable(R.drawable.marker));
((ViewGroup)v).addView(iv);
//create a bitmap from relative layout but the new bitmap is without marker
Bitmap b1 = Bitmap.createBitmap(rr.getWidth(), rr.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b1);
((ViewGroup)v).draw(c);
}
return false;
}
答案 0 :(得分:0)
这是因为动态添加标记到布局,添加动态视图有一些延迟。这就是没有标记创建位图的原因。在第二次触摸时,将创建单个标记位图。解决方案是在延迟一段时间后保存位图。
解决方案在这里:
private Handler handler = new Handler(); //handler object in global
rr.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN){
int x = (int) event.getX() ;
int y = (int) event.getY();
RelativeLayout.LayoutParams lp =new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);; //Assuming you use a RelativeLayout
ImageView iv=new ImageView(getApplicationContext());
lp.setMargins(x,y,0,0);
iv.setLayoutParams(lp);
iv.setImageDrawable(getResources().getDrawable(R.drawable.marker));
((ViewGroup)v).addView(iv);
//run handler after 1000 milli seconds i.e 1 sec
handler.postDelayed(runnable, 1000);
}
return false;
}
private Runnable runnable = new Runnable() {
@Override
public void run() {
//wrote your block of code here
//create a bitmap from relative layout but the new bitmap is without marker
Bitmap b1 = Bitmap.createBitmap(rr.getWidth(), rr.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b1);
((ViewGroup)v).draw(c);
}
};