在android中保存用户在fingerPaint api demos中制作的图像

发布于 2024-10-17 14:51:46 字数 5444 浏览 1 评论 0原文

嘿伙计们 我正在尝试构建一个签名任务应用程序。 用户将在其中创建触摸签名,并且该位图应保存在手机中。 我创建了 2 个类文件,其中一个具有与 Fingerpaint 应用程序中的自定义视图相同的自定义视图,并调用 main.xml 文件中的视图。

在我的主应用程序类文件中,我有菜单按钮,单击该按钮会将位图保存在 sdcard 中。以下是代码:-

package org.testCircle;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Bundle;
import android.provider.MediaStore.Images;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

public class testCircle extends Activity {
    TextView tv;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(new customView(this));
        setContentView(R.layout.main);
    }
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        menu.add(0, 1, 0, "save").setShortcut('3', 'c');
        return true;
    }
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case 1:
            //new ColorPickerDialog(this, this, mPaint.getColor()).show();
            fingerPaint cv = new fingerPaint(this);
            Bitmap viewBitmap = Bitmap.createBitmap(480, 800,Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(viewBitmap);
            cv.draw(canvas);
            String url = Images.Media.insertImage(getContentResolver(), viewBitmap, "title", null);
            Toast.makeText(testCircle.this, url, Toast.LENGTH_LONG).show();
            return true;
    }
        return super.onOptionsItemSelected(item);
}
}

自定义视图:-

package org.testCircle;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class fingerPaint extends View {
    Paint mPaint;

    private static final float MINP = 0.25f;
    private static final float MAXP = 0.75f;

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

    public fingerPaint(Context c) {
        super(c);
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
        mPaint.setColor(0xFFFF0000);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
        mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setStrokeWidth(12);
        mBitmap = Bitmap.createBitmap(320, 480, Bitmap.Config.ARGB_8888);
        mCanvas = new Canvas(mBitmap);
        mPath = new Path();
        mBitmapPaint = new Paint(Paint.DITHER_FLAG);
    }

    public fingerPaint(Context c , AttributeSet attrs){
        super(c , attrs);
         mPaint = new Paint();
         mPaint.setAntiAlias(true);
         mPaint.setDither(true);
         mPaint.setColor(0xFFFF0000);
         mPaint.setStyle(Paint.Style.STROKE);
         mPaint.setStrokeJoin(Paint.Join.ROUND);
         mPaint.setStrokeCap(Paint.Cap.ROUND);
         mPaint.setStrokeWidth(12);
         mBitmap = Bitmap.createBitmap(320, 480, Bitmap.Config.ARGB_8888);
         mCanvas = new Canvas(mBitmap);
         mPath = new Path();
         mBitmapPaint = new Paint(Paint.DITHER_FLAG);
    }

    public void onerase(){
        mCanvas=null;
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawColor(0xFFAAAAAA);

        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;
        }
        mCanvas.drawBitmap(mBitmap, mX, mY, mPaint);

    }
    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();
                Bundle b = new Bundle();

                break;
        }
        return true;
    }

}

Hey guys
I am trying to build a signature task application .
In which the user will create the signature on touch and that bitmap should be saved in the phone.
I have created 2 class files one having the custom view the same as the one in fingerpaint application and calling the view in main.xml file.

In my main application class file i have menu button which on click saves the bitmap in sdcard . The following is the code :-

package org.testCircle;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Bundle;
import android.provider.MediaStore.Images;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

public class testCircle extends Activity {
    TextView tv;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(new customView(this));
        setContentView(R.layout.main);
    }
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        menu.add(0, 1, 0, "save").setShortcut('3', 'c');
        return true;
    }
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case 1:
            //new ColorPickerDialog(this, this, mPaint.getColor()).show();
            fingerPaint cv = new fingerPaint(this);
            Bitmap viewBitmap = Bitmap.createBitmap(480, 800,Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(viewBitmap);
            cv.draw(canvas);
            String url = Images.Media.insertImage(getContentResolver(), viewBitmap, "title", null);
            Toast.makeText(testCircle.this, url, Toast.LENGTH_LONG).show();
            return true;
    }
        return super.onOptionsItemSelected(item);
}
}

Custom View :-

package org.testCircle;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class fingerPaint extends View {
    Paint mPaint;

    private static final float MINP = 0.25f;
    private static final float MAXP = 0.75f;

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

    public fingerPaint(Context c) {
        super(c);
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
        mPaint.setColor(0xFFFF0000);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
        mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setStrokeWidth(12);
        mBitmap = Bitmap.createBitmap(320, 480, Bitmap.Config.ARGB_8888);
        mCanvas = new Canvas(mBitmap);
        mPath = new Path();
        mBitmapPaint = new Paint(Paint.DITHER_FLAG);
    }

    public fingerPaint(Context c , AttributeSet attrs){
        super(c , attrs);
         mPaint = new Paint();
         mPaint.setAntiAlias(true);
         mPaint.setDither(true);
         mPaint.setColor(0xFFFF0000);
         mPaint.setStyle(Paint.Style.STROKE);
         mPaint.setStrokeJoin(Paint.Join.ROUND);
         mPaint.setStrokeCap(Paint.Cap.ROUND);
         mPaint.setStrokeWidth(12);
         mBitmap = Bitmap.createBitmap(320, 480, Bitmap.Config.ARGB_8888);
         mCanvas = new Canvas(mBitmap);
         mPath = new Path();
         mBitmapPaint = new Paint(Paint.DITHER_FLAG);
    }

    public void onerase(){
        mCanvas=null;
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawColor(0xFFAAAAAA);

        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;
        }
        mCanvas.drawBitmap(mBitmap, mX, mY, mPaint);

    }
    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();
                Bundle b = new Bundle();

                break;
        }
        return true;
    }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

意犹 2024-10-24 14:51:46

这是执行此操作的源代码

LinearLayout v = (LinearLayout) findViewById(R.id.mainLayout);
v.setDrawingCacheEnabled(true);
// this is the important code :)
// Without it the view will have a
// dimension of 0,0 and the bitmap will
// be null
v.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
v.layout(0, 0, v.getWidth(), v.getHeight());
v.buildDrawingCache(true);
Bitmap bm = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false);
if (bm != null) {
    try {
        String path = Environment.getExternalStorageDirectory().toString();
        OutputStream fOut = null;
        File file = new File(path, "screentest.jpg");
        fOut = new FileOutputStream(file);
        bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
        fOut.flush();
        fOut.close();
        Log.e("ImagePath", "Image Path : " + MediaStore.Images.Media.insertImage( getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName()));
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

Here is the source code to do that

LinearLayout v = (LinearLayout) findViewById(R.id.mainLayout);
v.setDrawingCacheEnabled(true);
// this is the important code :)
// Without it the view will have a
// dimension of 0,0 and the bitmap will
// be null
v.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
v.layout(0, 0, v.getWidth(), v.getHeight());
v.buildDrawingCache(true);
Bitmap bm = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false);
if (bm != null) {
    try {
        String path = Environment.getExternalStorageDirectory().toString();
        OutputStream fOut = null;
        File file = new File(path, "screentest.jpg");
        fOut = new FileOutputStream(file);
        bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
        fOut.flush();
        fOut.close();
        Log.e("ImagePath", "Image Path : " + MediaStore.Images.Media.insertImage( getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName()));
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}
小糖芽 2024-10-24 14:51:46

您的 FingerPaint 类中有一个 Bitmap 对象。将 FileOutputStream 实例化到您想要保存到的位置,并使用适当的选项和输出流调用 mBitmap.compress 方法。请记住关闭您的信息流。

You've got a Bitmap object in your fingerPaint class. Instantiate a FileOutputStream to the location you'd like to save to, and call mBitmap.compress method with the appropriate options and your output stream. Remember to close your stream.

ヅ她的身影、若隐若现 2024-10-24 14:51:46
    final View content = findViewById(R.id.layoutFP);
    content.setDrawingCacheEnabled(true);
    Bitmap bitmap = content.getDrawingCache();
    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/saved_images");    
    myDir.mkdirs();
    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);
    String fname = "Image-"+ n +".jpg";
    File file = new File (myDir, fname);
    if (file.exists ()) file.delete (); 
    try {
           FileOutputStream out = new FileOutputStream(file);
           bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
           out.flush();
           out.close();
           content.invalidate(); 
           sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));

    } catch (Exception e) {
           e.printStackTrace();
    }finally{
        content.setDrawingCacheEnabled(false);                          
    }

最后在清单文件中添加权限:

<使用权限 android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    final View content = findViewById(R.id.layoutFP);
    content.setDrawingCacheEnabled(true);
    Bitmap bitmap = content.getDrawingCache();
    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/saved_images");    
    myDir.mkdirs();
    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);
    String fname = "Image-"+ n +".jpg";
    File file = new File (myDir, fname);
    if (file.exists ()) file.delete (); 
    try {
           FileOutputStream out = new FileOutputStream(file);
           bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
           out.flush();
           out.close();
           content.invalidate(); 
           sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));

    } catch (Exception e) {
           e.printStackTrace();
    }finally{
        content.setDrawingCacheEnabled(false);                          
    }

Finally add permission in your Manifest file:

< uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文