如何在imageview上与android中的手指一起画线

how to draw line on imageview along with finger in android(如何在imageview上与android中的手指一起画线)

本文介绍了如何在imageview上与android中的手指一起画线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我想用手指在 imageview 上画线.我想要如下输出:

在这个屏幕中,鱼是图像视图,红线是画线.所以我按照下面的链接来开发应用程序.

类 DrawingView 扩展 View {绘制 mPaint;//MaskFilter mEmboss;//MaskFilter mBlur;位图 mBitmap;帆布 mCanvas;路径 mPath;绘制 mBitmapPaint;公共绘图视图(上下文上下文){超级(上下文);//TODO 自动生成的构造函数存根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(20);mPath = 新路径();mBitmapPaint = new Paint();mBitmapPaint.setColor(Color.RED);}@覆盖受保护的无效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 = 新画布(mBitmap);}@覆盖公共无效绘制(帆布画布){//TODO 自动生成的方法存根超级画(画布);canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);canvas.drawPath(mPath, mPaint);}私人浮动 mX, mY;私有静态最终浮点 TOUCH_TOLERANCE = 4;私人无效触摸开始(浮动x,浮动y){//mPath.reset();mPath.moveTo(x, y);mX = x;米 = y;}私人无效触摸移动(浮动x,浮动y){浮动 dx = Math.abs(x - mX);浮动 dy = Math.abs(y - mY);如果(dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE){mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);mX = x;米 = y;}}私人无效touch_up(){mPath.lineTo(mX, mY);//提交到我们屏幕外的路径mCanvas.drawPath(mPath, mPaint);//mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SCREEN));//杀死它,这样我们就不会重复绘制mPath.reset();//mPath= new Path();}@覆盖公共布尔 onTouchEvent(MotionEvent 事件){浮动 x = event.getX();浮动 y = event.getY();开关 (event.getAction()) {案例 MotionEvent.ACTION_DOWN:touch_start(x, y);无效();休息;案例 MotionEvent.ACTION_MOVE:触摸移动(x,y);无效();休息;案例 MotionEvent.ACTION_UP:润色();无效();休息;}返回真;}}

您的绘图视图已设置.在graphics文件夹下sdk上的sample中研究fingerpaint.java.

生成的快照.您在背景中看到的是图像.在前景我画了嗨.我在拐角处画线.如果你能看出来它是红色的.

画出看起来像边框的线条.将油漆的描边宽度设置为您喜欢的任何值.同样,您可以通过更改 x1,y1 和 x2,y2 坐标来绘制所需的线条.

Display display = ( (Activity) mcontext).getWindowManager().getDefaultDisplay();浮动 w = display.getWidth();浮动 h = display.getHeight();canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);canvas.drawLine(0, 0, w, 0,mBitmapPaint);canvas.drawLine(0, 0, 0, h,mBitmapPaint);canvas.drawLine(w,h,w,0,mBitmapPaint);canvas.drawLine(w, h, 0,h , mBitmapPaint);

从图库中获取图片

文件 fp;可绘制的 d;公共无效 setImagefrmGallery() {//打开画廊浏览器意图意图 = new Intent();intent.setType("图片/*");意图.setAction(意图.ACTION_GET_CONTENT);startActivityForResult(Intent.createChooser(intent, "选择图片"),1);//要处理从浏览器中选择图像时,请将以下内容添加到您的 Activity}@覆盖public void onActivityResult(int requestCode, int resultCode, Intent data) {if (resultCode == RESULT_OK) {如果(请求代码 == 1){//currImageURI 是我用来保存图像的 content://URI 的全局变量Uri currImageURI = data.getData();System.out.println("你好======="+getRealPathFromURI(currImageURI));字符串 s= getRealPathFromURI(currImageURI);文件文件 = 新文件;如果 (file.exists()) {fp=file.getAbsolutePath();d = Drawable.createFromPath(file.getAbsolutePath());mDrawingPad.setBackgroundDrawable(d);} 别的 {System.out.println("找不到文件");}}}}//并将图像URI转换为图像文件的直接文件系统路径公共字符串 getRealPathFromURI(Uri contentUri) {//可以发布图片字符串 [] proj={MediaStore.Images.Media.DATA};光标 cursor = managedQuery( contentUri,proj,//返回哪些列null,//WHERE 子句;返回哪些行(所有行)null,//WHERE 子句选择参数(无)空值);//Order-by 子句(按名称升序)int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);cursor.moveToFirst();返回 cursor.getString(column_index);}

In my app I want to draw line on imageview along with finger. I want the output like the following:

In this screen fish is the imageview and red lines are drawing lines. So I followed the link below to develop the app link. This is my code:

public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.addphoto);

    btnAddPhoto=(Button)findViewById(R.id.add);
    btnEdit=(Button)findViewById(R.id.edit);
    imageView=(ImageView)findViewById(R.id.photo);

    btnAddPhoto.setOnClickListener(this);
    btnEdit.setOnClickListener(this);
    imageView.setOnTouchListener(this);         
}

    @Override
public void onWindowFocusChanged(boolean hasFocus){
    width=imageView.getWidth();
    height=imageView.getHeight();

    Log.e("heightttt",""+height);
    Log.e("Widthhhh",""+width);

}

    @Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    if(v.equals(btnAddPhoto)){

        popup.setVisibility(View.VISIBLE);
    }

    if(v.equals(btnEdit)){
       bitmap = Bitmap.createBitmap((int) width, (int) height,Bitmap.Config.ARGB_8888);
        canvas = new Canvas(bitmap);
        paint = new Paint();
        paint.setColor(Color.BLACK);
        imageView.setImageBitmap(bitmap);
        imageView.setOnTouchListener(this);
    }
}

    public boolean onTouch(View v, MotionEvent event) {
        int action = event.getAction();
        switch (action) {
        case MotionEvent.ACTION_DOWN:
          downx = event.getX();
          downy = event.getY();
          break;
        case MotionEvent.ACTION_MOVE:
          break;
        case MotionEvent.ACTION_UP:
          upx = event.getX();
          upy = event.getY();
          canvas.drawLine(downx, downy, upx, upy, paint);
          imageView.invalidate();
          break;
        case MotionEvent.ACTION_CANCEL:
          break;
        default:
          break;
        }
        return true;
      }

In this coding whenever I run the application the below screen will be open.

Then by using add button I added the photo from my gallery. This is below screen.

Then whenever I click edittool button the fish imageview gone and I could draw the straight lines only like the following. But I want to draw lines on imageview along with finger like first screen.

Please anybody help me. I am new to android. Thanks for any help.

解决方案

You should override the onDraw method of your view.

screen_drawing_room.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rlid"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout   <!--set background for the bottom layout set image here. -->
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="bottom"
    android:orientation="vertical"
    android:weightSum="1.0" >

    <LinearLayout
        android:id="@+id/view_drawing_pad" <!--your drawing pad on foreground -->
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
    </LinearLayout>
</LinearLayout>
</RelativeLayout

In your activities onCreate()

DrawingView mDrawingView=new DrawingView(this);
setContentView(R.layout.screen_drawing_room);    
LinearLayout mDrawingPad=(LinearLayout)findViewById(R.id.view_drawing_pad);
mDrawingPad.addView(mDrawingView);

DrawingView.java

Define your DrawingView. The below can be used for freehand drawing. Modify the same to draw lines, texts and fill color( closed area). For flood Fill see the accepted answer in the link android using flood fill algorithm getting out of memory exception.

class DrawingView extends View {
    Paint       mPaint;
    //MaskFilter  mEmboss;
    //MaskFilter  mBlur;
    Bitmap  mBitmap;
    Canvas  mCanvas;
    Path    mPath;
    Paint   mBitmapPaint;

    public DrawingView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        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(20);

        mPath = new Path();
        mBitmapPaint = new Paint();
        mBitmapPaint.setColor(Color.RED);
    }
    @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
    public void draw(Canvas canvas) {
        // TODO Auto-generated method stub
        super.draw(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);
        //mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SCREEN));
        // kill this so we don't double draw
        mPath.reset();
       // mPath= new Path();
    }

    @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;
    }   
}

Your Drawing view is set. Study the fingerpaint.java from the sample on sdk under the graphics folder.

Resulting sanpshot. What you see in the background is a image. On the foreground I draw hi. I have draw lines to the corner. If you can make out it is red.

Draw lines which look like border. Set Stroke width for the paint to whatever you like. Similarly you can draw lines where you want by changing the x1,y1 and x2,y2 co-ordinates.

Display display = ( (Activity) mcontext).getWindowManager().getDefaultDisplay();  
float w = display.getWidth(); 
float h = display.getHeight();
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.drawLine(0, 0, w, 0,mBitmapPaint);
canvas.drawLine(0, 0, 0, h,mBitmapPaint);
canvas.drawLine(w,h,w,0,mBitmapPaint);
canvas.drawLine(w, h, 0,h , mBitmapPaint);

Edit:

To get image from gallery

File fp;
Drawable d;   

public void  setImagefrmGallery() {
    // To open up a gallery browser
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"),1);
    // To handle when an image is selected from the browser, add the following to your Activity 
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == 1) {
            // currImageURI is the global variable I�m using to hold the content:// URI of the image
            Uri currImageURI = data.getData();
            System.out.println("Hello======="+getRealPathFromURI(currImageURI));
            String s= getRealPathFromURI(currImageURI);
            File file = new File(s);

            if (file.exists()) {
                fp=file.getAbsolutePath();
                d = Drawable.createFromPath(file.getAbsolutePath());
                mDrawingPad.setBackgroundDrawable(d);
            } else {
                System.out.println("File Not Found");
            }
        }
    }
}

// And to convert the image URI to the direct file system path of the image file
public String getRealPathFromURI(Uri contentUri) {
    // can post image
    String [] proj={MediaStore.Images.Media.DATA};
    Cursor cursor = managedQuery( contentUri,
            proj, // Which columns to return
            null, // WHERE clause; which rows to return (all rows)
            null, // WHERE clause selection arguments (none)
            null); // Order-by clause (ascending by name)
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index); 
}

这篇关于如何在imageview上与android中的手指一起画线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在imageview上与android中的手指一起画线

基础教程推荐