在画布上绘图并保存图像

时间:2011-09-13 11:55:23

标签: android graphics android-canvas handwriting

我是Android Graphics类的新手。我想使用触摸事件绘制图像(实际上是签名类型),并希望在我想保存时将其保存在SD卡上。我已经通过网络扫描了任何这样的教程,但我还没有找到。谁能告诉我如何使用触摸事件在画布上绘制并保存它。

任何教程或示例代码都会有很大帮助。

2 个答案:

答案 0 :(得分:21)

我在android开发人员身上看到了非常好的代码,但我再也找不到它了......它的输出是bezier曲线,所以它会非常流畅。这是我编辑的代码:

public class MyDrawView extends View {

private Bitmap  mBitmap;
private Canvas  mCanvas;
private Path    mPath;
private Paint   mBitmapPaint;
private Paint   mPaint;

public MyDrawView(Context c) {
    super(c);

    mPath = new Path();
    mBitmapPaint = new Paint(Paint.DITHER_FLAG);

    mPaint = new Paint();
    mPaint.setAntiAlias(true);
    mPaint.setDither(true);
    mPaint.setColor(0xFF000000);
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setStrokeJoin(Paint.Join.ROUND);
    mPaint.setStrokeCap(Paint.Cap.ROUND);
    mPaint.setStrokeWidth(3);
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    mCanvas = new Canvas(mBitmap);
}

@Override
protected void onDraw(Canvas canvas) {
    canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);

    canvas.drawPath(mPath, mPaint);
}

private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;

private void touch_start(float x, float y) {
    mPath.reset();
    mPath.moveTo(x, y);
    mX = x;
    mY = y;
}
private void touch_move(float x, float y) {
    float dx = Math.abs(x - mX);
    float dy = Math.abs(y - mY);
    if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
        mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
        mX = x;
        mY = y;
    }
}
private void touch_up() {
    mPath.lineTo(mX, mY);
    // commit the path to our offscreen
    mCanvas.drawPath(mPath, mPaint);
    // kill this so we don't double draw
    mPath.reset();
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    float x = event.getX();
    float y = event.getY();

    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            touch_start(x, y);
            invalidate();
            break;
        case MotionEvent.ACTION_MOVE:
            touch_move(x, y);
            invalidate();
            break;
        case MotionEvent.ACTION_UP:
            touch_up();
            invalidate();
            break;
    }
    return true;
}

public void clear(){
    mBitmap.eraseColor(Color.TRANSPARENT);
    invalidate();
    System.gc();
}}

然后在onCreate of activity中你想用它来写下这样的东西:

RelativeLayout parent = (RelativeLayout) findViewById(R.id.signImageParent);
myDrawView = new MyDrawView(this);
parent.addView(myDrawView);

此视图是透明的,并使用黑色绘画用手指绘制。因此,如果你想看到你画的东西,只需在这个视图的背景上绘制一个白色或灰色的位图(你只需在onDraw的beginnig中添加一行),或者你可以使用父级的背景。

然后,当您想要根据绘制的图像创建图像时,只需调用

即可
parent.setDrawingCacheEnabled(true);
Bitmap b = parent.getDrawingCache();

FileOutputStream fos = null;
try {
fos = new FileOutputStream(getFileName());
} catch (FileNotFoundException e) {
e.printStackTrace();
}

b.compress(CompressFormat.PNG, 95, fos);

这取决于您想要输出的内容,您可以使用此代码或代替 parent ,您可以使用 myDrawView 执行此操作,您只需获得图像即可没有背景绘制(因为我们的myDrawView背景透明)。

希望这会有所帮助。随意留下反馈。

答案 1 :(得分:20)

绘图事物

Scribbler.java:

package org.yourpackage.scribble;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;

public class Scribbler extends Activity {
    DrawView drawView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        drawView = new DrawView(this);
        drawView.setBackgroundColor(Color.WHITE);
        setContentView(drawView);
        drawView.requestFocus();

    }
}

DrawView.java:

package org.yourpackage.scribble;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

public class DrawView extends View implements OnTouchListener {
    List<Point> points = new ArrayList<Point>();
    Paint paint = new Paint();

    public DrawView(Context context) {
        super(context);
        setFocusable(true);
        setFocusableInTouchMode(true);
        this.setOnTouchListener(this);
        paint.setColor(Color.BLACK);
    }

    @Override
    public void onDraw(Canvas canvas) {
        for (Point point : points) {
            canvas.drawCircle(point.x, point.y, 2, paint);  
        }
    }

    public boolean onTouch(View view, MotionEvent event) {
        Point point = new Point();
        point.x = event.getX();
        point.y = event.getY();
        points.add(point);
        invalidate();
        return true;
    }
}

class Point {
    float x, y;
}

的AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="org.yourpackage.scribble"
      android:versionCode="1"
      android:versionName="1.0">
    <application>
        <activity android:name=".Scribbler">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-sdk android:minSdkVersion="3" />
</manifest> 

..会给你这样的东西:

alt text

您可能想要绘制线条而不是像素

保存的东西

要实施保存,您可以将Bitmap传递到Canvas构造函数,然后使用compress Bitmap创建可以写入SD卡的OutputStream的方法

编辑回答你的评论:
当然,您可以使用XML来定义布局,因为DrawView扩展了View,您可以在布局xml文件中使用它。 main.xml布局文件

的示例
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:id="@+id/linearLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/gradient"
    >

    <Button android:text="Button" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
    <org.yourpackage.scribble.DrawView android:id="@+id/drawView1" android:layout_width="wrap_content" android:layout_height="wrap_content">        </at.gru.android.drawdemo.DrawView>
</LinearLayout>

给你这样的东西:
enter image description here
您只需要一个额外的contstructor public DrawView(Context context, AttributeSet attrSet)