Android - 如何在用户的点击上为图像的整个区域着色并将其置于场景中心?

时间:2013-06-08 11:40:31

标签: java android android-layout android-imageview flood-fill

我正在开展一个小项目,用户可以通过点击触摸屏为白色图像的整个区域着色。

这是图片的一个例子:

enter image description here

这并不难,事实上我使用泛光填充算法为由黑线分隔的相同颜色区域着色。 我的问题是在屏幕中将我修改的图像居中。

我使用以下代码:

JAVA:

import java.util.LinkedList;
import java.util.Queue;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;

public class Main extends Activity {

private RelativeLayout dashBoard;
private MyView myView;
public ImageView image;

Button b_red, b_blue, b_green, b_orange, b_clear;

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

    myView = new MyView(this);
    setContentView(R.layout.activity_main);
    findViewById(R.id.dashBoard);
    findViewById(R.id.myImage);


    b_red = (Button) findViewById(R.id.b_red);
    b_blue = (Button) findViewById(R.id.b_blue);
    b_green = (Button) findViewById(R.id.b_green);
    b_orange = (Button) findViewById(R.id.b_orange);

    b_red.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            myView.changePaintColor(0xFFFF0000);
        }
    });

    b_blue.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            myView.changePaintColor(0xFF0000FF);
        }
    });

    b_green.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            myView.changePaintColor(0xFF00FF00);
        }
    });

    b_orange.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            myView.changePaintColor(0xFFFF9900);
        }
    });

    dashBoard = (RelativeLayout) findViewById(R.id.dashBoard);
    image = (ImageView) findViewById(R.id.myImage);
    dashBoard.addView(myView);
}

public class MyView extends View {

    private Paint paint;
    private Path path;
    public Bitmap mBitmap;
    public ProgressDialog pd;
    final Point p1 = new Point();
    public Canvas canvas;

    //Bitmap mutableBitmap ;
    public MyView(Context context) {

        super(context);

        this.paint = new Paint();
        this.paint.setAntiAlias(true);
        pd = new ProgressDialog(context);
        this.paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeJoin(Paint.Join.ROUND);
        paint.setStrokeWidth(5f);
        mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.forme).copy(Bitmap.Config.ARGB_8888, true);
        this.path = new Path();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        this.canvas = canvas;
        this.paint.setColor(Color.RED);

        canvas.drawBitmap(mBitmap, 0, 0, paint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        float x = event.getX();
        float y = event.getY();

        switch (event.getAction()) {

            case MotionEvent.ACTION_DOWN:

                p1.x = (int) x;
                p1.y = (int) y;
                final int sourceColor = mBitmap.getPixel((int) x, (int) y);
                final int targetColor = paint.getColor();
                new TheTask(mBitmap, p1, sourceColor, targetColor).execute();
                invalidate();
        }
        return true;
    }

    public void clear() {
        path.reset();
        invalidate();
    }

    public int getCurrentPaintColor() {
        return paint.getColor();
    }

    public void changePaintColor(int color){
        this.paint.setColor(color);
    }

    class TheTask extends AsyncTask<Void, Integer, Void> {

        Bitmap bmp;
        Point pt;
        int replacementColor, targetColor;

        public TheTask(Bitmap bm, Point p, int sc, int tc) {
            this.bmp = bm;
            this.pt = p;
            this.replacementColor = tc;
            this.targetColor = sc;
            pd.setMessage("Filling....");
            pd.show();
        }

        @Override
        protected void onPreExecute() {
            pd.show();

        }

        @Override
        protected void onProgressUpdate(Integer... values) {

        }

        @Override
        protected Void doInBackground(Void... params) {
            FloodFill f = new FloodFill();
            f.floodFill(bmp, pt, targetColor, replacementColor);
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            pd.dismiss();
            invalidate();
        }
    }
}

// Flood fill
public class FloodFill {

    public void floodFill(Bitmap image, Point node, int targetColor, int replacementColor) {

        int width = image.getWidth();
        int height = image.getHeight();
        int target = targetColor;
        int replacement = replacementColor;

        if (target != replacement) {
            Queue<Point> queue = new LinkedList<Point>();
            do {

                int x = node.x;
                int y = node.y;
                while (x > 0 && image.getPixel(x - 1, y) == target) {
                    x--;
                }

                boolean spanUp = false;
                boolean spanDown = false;
                while (x < width && image.getPixel(x, y) == target) {
                    image.setPixel(x, y, replacement);
                    if (!spanUp && y > 0 && image.getPixel(x, y - 1) == target) {
                        queue.add(new Point(x, y - 1));
                        spanUp = true;
                    } else if (spanUp && y > 0 && image.getPixel(x, y - 1) != target) {
                        spanUp = false;
                    }
                    if (!spanDown && y < height - 1 && image.getPixel(x, y + 1) == target) {
                        queue.add(new Point(x, y + 1));
                        spanDown = true;
                    } else if (spanDown && y < (height - 1) && image.getPixel(x, y + 1) != target) {
                        spanDown = false;
                    }
                    x++;
                }

            } while ((node = queue.poll()) != null);
        }
    }
}
}

XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawingLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#969696"
tools:context=".Main" >

<RelativeLayout
    android:id="@+id/dashBoard"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/b_red"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:layout_marginBottom="10dp"
    android:background="#DDDDDD" >

    <ImageView
        android:id="@+id/myImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true" />

</RelativeLayout>

<Button
    android:id="@+id/b_red"
    android:layout_width="65dp"
    android:layout_height="40dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:background="#FF0000" />

<Button
    android:id="@+id/b_green"
    android:layout_width="65dp"
    android:layout_height="40dp"
    android:layout_alignParentBottom="true"
    android:layout_toRightOf="@+id/b_red"
    android:background="#00FF00" />

<Button
    android:id="@+id/b_blue"
    android:layout_width="65dp"
    android:layout_height="40dp"
    android:layout_alignParentBottom="true"
    android:layout_toRightOf="@+id/b_green"
    android:background="#0000FF" />

<Button
    android:id="@+id/b_orange"
    android:layout_width="65dp"
    android:layout_height="40dp"
    android:layout_alignParentBottom="true"
    android:layout_toRightOf="@+id/b_blue"
    android:background="#FF9900" />

<Button
    android:id="@+id/button5"
    android:layout_width="60dp"
    android:layout_height="40dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:text="Clear" />

</RelativeLayout>

当我运行项目时,我得到:

enter image description here

正如您所看到的,图像未在所有浅灰色区域中扩展!我想这个问题是由于添加到包含ImageView的RelativeLayout的一般视图的交错引起的。

你能告诉我怎样才能将图像强加到所有浅灰色区域?如何在不使用 RelativeLayout 组件的情况下与 ImageVie 组件交互?

感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

<强>更新

要获得MyView的大小,只需覆盖onMeasure()方法,如下所示:

@Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);

             w = widthMeasureSpec - MeasureSpec.EXACTLY;
             h = heightMeasureSpec - MeasureSpec.EXACTLY;

            Log.d("Dim", Integer.toString(w) + " | " + Integer.toString(h));
        }

好吧,我发现了一些我觉得可能对你有帮助的东西。你的Bitmap没有填充画布的原因是因为它显然很小。通常Canvas.drawBitmap()会占用与图像一样大的空间。因此,为了使用位图填充屏幕,您应该在绘制之前缩放它。

我这样做的很快:

mBitmap = BitmapFactory.decodeResource(getResources(),
                       R.drawable.forme).copy(Bitmap.Config.ARGB_8888, true);
this.path = new Path();

// Get the screen dimension
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
h = displaymetrics.heightPixels;
w = displaymetrics.widthPixels;

scaledBitmap = Bitmap.createScaledBitmap(mBitmap, w, h, false);

然后在onDraw()中,您将绘制缩放的位图:

canvas.drawBitmap(scaledBitmap, 0, 0, paint);

另外,请务必将scaledBitmap发送到AsyncTask

...
final int sourceColor = scaledBitmap.getPixel((int) x, (int) y); //<- HERE
...
new TheTask(scaledBitmap, p1, sourceColor, targetColor).execute(); //<- AND HERE

重要

这里我得到了缩放位图的屏幕尺寸。但是你可以在下面看到它并不好。您的画布应该只占用dashBoard空间而不是整个屏幕。因此,我建议您改为查找dashBoard维,并相应地缩放位图。

PaintTest

答案 1 :(得分:0)

尝试以下方法:

  • 使用LinearLayoutorientation="vertical"
  • 替换主要布局
  • 移除包裹RelativeLayout
  • ImageView
  • layout_width上设置layout_height"match_parent"ImageView,并将layout_weight添加到值"1"
  • 使用LinearLayout orientation="horizontal"layout_width="match_parent"layout_height="wrap_content"换成新的adjustViewBounds按钮。

然后使用scaleType的{​​{1}}和ImageView属性进行调整,以根据需要进行调整。

HTH