【发布时间】:2015-09-22 21:48:38
【问题描述】:
我已尝试以下链接 - draw-on-a-canvas-with-bitmap-as-background 和 saving-bitmap-drawn-on-canvas
第一个对我有用并解决了问题,让我不仅可以在位图图像上绘制,还可以使用绘制的线条进行保存。
最近,我搞砸了布局,一切都恢复了原样。尽管挣扎了几天,但没有解决方案,即它保存了位图图像,但在其上绘制的任何内容都不会显示在图像中。相同的代码,但仍然不起作用,我不知道为什么。
下面是我的代码:
class MyView extends View
{
public MyView(Context context)
{
super(context);
paint = new Paint();
paint.setDither(true);
paint.setStrokeWidth(4);
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.RED);
cw = new ContextWrapper(context);
canvas=new Canvas();
path = new Path();
paths = new ArrayList<>();
opt = new BitmapFactory.Options();
opt.inMutable = true;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
opt = new BitmapFactory.Options();
opt.inMutable = true;
bmp = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.fabialeft, opt);
bmp2 = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), bmp.getConfig());
bmp2 = Bitmap.createBitmap(bmp);
canvas = new Canvas(bmp2);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(bmp2, 0, 0, paint);
for(Path p:paths)
canvas.drawPath(p, paint);
}
public void Save() {
directory = cw.getDir("final", Context.MODE_PRIVATE);
file = new File(directory,"fabialeft");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
bmp2.compress(Bitmap.CompressFormat.JPEG, 100, fos);
System.out.println("Saved to --" + file);
Toast.makeText(getContext(), file.toString(), Toast.LENGTH_SHORT).show();
fos.close();
}catch (FileNotFoundException e)
{
System.out.println(e);
System.out.println("Saved" + file);
Toast.makeText(getContext(), "FNF EXCEPTION", Toast.LENGTH_SHORT).show();
}catch (IOException ioe)
{
System.out.println("ERROR" + file);Toast.makeText(getContext(), "IO EXCEPTION", Toast.LENGTH_SHORT).show();
}
}
public void Draw() {
Toast.makeText(getApplicationContext(), "DRAWING...", Toast.LENGTH_SHORT).show();
path.moveTo(100, 100);
path.lineTo(300, 300);
paths.add(path);
invalidate();
}
}
布局文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:id="@+id/relayout1"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="@+id/button"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Draw"
android:id="@+id/button2" />
</RelativeLayout>
【问题讨论】:
标签: android bitmap android-canvas