在Canvas中组合图像,然后使用Android Studio通过ImageView进行查看



我想通过将图像放在Canvas中的顶部来组合图像,然后使用ImageView查看组合。我所知道的是,如果你将第一个位图设置到画布中,你所做的一切都将添加到第一个位图中。我只得到错误:PointerException:尝试在空对象引用上调用虚拟方法"int android.graphics.Bitmap.getWidth((">

ImageView mainImage = (ImageView) view.findViewById(R.id.mainImage);
Bitmap bottomImage = BitmapFactory.decodeFile("image1.png");
Bitmap topImage = BitmapFactory.decodeFile("image2.png");
Bitmap tempBitmap = Bitmap.createBitmap(bottomImage.getWidth(), bottomImage.getHeight(), Bitmap.Config.RGB_565);
Canvas tempCanvas = new Canvas(tempBitmap);
tempCanvas.drawBitmap(bottomImage, 0, 0, null);
tempCanvas.drawBitmap(topImage, 0, 0, null);
mainImage.setImageBitmap(bitmap);

尝试低于代码

public Bitmap drawImageOnImage(Bitmap background, Bitmap pic, int x_to_draw, int y_to_draw, int width, int height)
{
try
{
Canvas newCanvas = new Canvas(background);
Bitmap img_bitmap = Bitmap.createScaledBitmap(pic, width, height, true);
newCanvas.drawBitmap(img_bitmap, x_to_draw, y_to_draw,new Paint());
}catch (Exception e)
{
System.out.println("Error Occured=>");
e.printStackTrace();
}
return background;
}

这里的函数采用两个输入位图,背景位图和另一个图像位图绘制在背景位图上。您将获得要为ImageView设置的组合位图。X和Y是顶部图像位图开始绘制的坐标。高度和宽度相同

经过一些实验,此代码运行良好。我添加了多个顶部图像。

private void drawAndView(ImageView imgView, Bitmap bottomImage, Bitmap[] topImages){
Bitmap tempBitmap = Bitmap.createBitmap(bottomImage.getWidth(), bottomImage.getHeight(), Bitmap.Config.RGB_565);
Canvas tempCanvas = new Canvas(tempBitmap);
tempCanvas.drawBitmap(bottomImage, 0, 0, null);
for (Bitmap bitmap : topImages){
tempCanvas.drawBitmap(bitmap, 0, 0, null);
}
imgView.setImageBitmap(tempBitmap);
}

相关内容

  • 没有找到相关文章

最新更新