I have a CustomView and an Image view. The CustomView is a ball that moves around the screen and bounces off the walls. The Image is a quarter circle that you can rotate in a circle on touch. I am trying to make my game so that when the filled pixels from the CustomView cross paths with the Filled pixels from the ImageView a collision is detected. The problem that I am having is I do not know how to retrieve where the filled pixels are on each view.
Here is my XML code
<com.leytontaylor.bouncyballz.AnimatedView
android:id="#+id/anim_view"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
/>
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/quartCircle"
android:layout_gravity="center_horizontal"
android:src="#drawable/quartercircle"
android:scaleType="matrix"/>
My MainActivity
public class MainActivity extends AppCompatActivity {
private static Bitmap imageOriginal, imageScaled;
private static Matrix matrix;
private ImageView dialer;
private int dialerHeight, dialerWidth;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// load the image only once
if (imageOriginal == null) {
imageOriginal = BitmapFactory.decodeResource(getResources(), R.drawable.quartercircle);
}
// initialize the matrix only once
if (matrix == null) {
matrix = new Matrix();
} else {
// not needed, you can also post the matrix immediately to restore the old state
matrix.reset();
}
dialer = (ImageView) findViewById(R.id.quartCircle);
dialer.setOnTouchListener(new MyOnTouchListener());
dialer.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
// method called more than once, but the values only need to be initialized one time
if (dialerHeight == 0 || dialerWidth == 0) {
dialerHeight = dialer.getHeight();
dialerWidth = dialer.getWidth();
// resize
Matrix resize = new Matrix();
resize.postScale((float) Math.min(dialerWidth, dialerHeight) / (float) imageOriginal.getWidth(), (float) Math.min(dialerWidth, dialerHeight) / (float) imageOriginal.getHeight());
imageScaled = Bitmap.createBitmap(imageOriginal, 0, 0, imageOriginal.getWidth(), imageOriginal.getHeight(), resize, false);
// translate to the image view's center
float translateX = dialerWidth / 2 - imageScaled.getWidth() / 2;
float translateY = dialerHeight / 2 - imageScaled.getHeight() / 2;
matrix.postTranslate(translateX, translateY);
dialer.setImageBitmap(imageScaled);
dialer.setImageMatrix(matrix);
}
}
});
}
MyOnTouchListener class:
private class MyOnTouchListener implements View.OnTouchListener {
private double startAngle;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
startAngle = getAngle(event.getX(), event.getY());
break;
case MotionEvent.ACTION_MOVE:
double currentAngle = getAngle(event.getX(), event.getY());
rotateDialer((float) (startAngle - currentAngle));
startAngle = currentAngle;
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
}
private double getAngle(double xTouch, double yTouch) {
double x = xTouch - (dialerWidth / 2d);
double y = dialerHeight - yTouch - (dialerHeight / 2d);
switch (getQuadrant(x, y)) {
case 1:
return Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI;
case 2:
return 180 - Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI;
case 3:
return 180 + (-1 * Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI);
case 4:
return 360 + Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI;
default:
return 0;
}
}
/**
* #return The selected quadrant.
*/
private static int getQuadrant(double x, double y) {
if (x >= 0) {
return y >= 0 ? 1 : 4;
} else {
return y >= 0 ? 2 : 3;
}
}
/**
* Rotate the dialer.
*
* #param degrees The degrees, the dialer should get rotated.
*/
private void rotateDialer(float degrees) {
matrix.postRotate(degrees, dialerWidth / 2, dialerHeight / 2);
dialer.setImageMatrix(matrix);
}
And my AnimatedView
public class AnimatedView extends ImageView {
private Context mContext;
int x = -1;
int y = -1;
private int xVelocity = 10;
private int yVelocity = 5;
private Handler h;
private final int FRAME_RATE = 60;
public AnimatedView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
h = new Handler();
}
private Runnable r = new Runnable() {
#Override
public void run() {
invalidate();
}
};
protected void onDraw(Canvas c) {
BitmapDrawable ball = (BitmapDrawable) mContext.getResources().getDrawable(R.drawable.smallerball);
if (x<0 && y <0) {
x = this.getWidth()/2;
y = this.getHeight()/2;
} else {
x += xVelocity;
y += yVelocity;
if ((x > this.getWidth() - ball.getBitmap().getWidth()) || (x < 0)) {
xVelocity = xVelocity*-1;
}
if ((y > this.getHeight() - ball.getBitmap().getHeight()) || (y < 0)) {
yVelocity = yVelocity*-1;
}
}
c.drawBitmap(ball.getBitmap(), x, y, null);
h.postDelayed(r, FRAME_RATE);
}
public float getX() {
return x;
}
public float getY() {
return y;
}
}
My question is: How can I retrieve the filled pixels from both of these views, and pass them through a function that detects a collision.
Thanks in advance for the help!:)
You could encapsulate your images with Array of points marking your border coordinates(and update them on move/calculate them based on origin) then you'll be able to decide whether oposing object are in touch or not(if any of oposing arrays share the same point)
You really need to define "filled pixels". I assume you mean the non-transparent pixels. The easiest way to find those, is by converting your entire view into a bitmap and iterating through its pixels. You can convert a View into a Bitmap like this:
private Bitmap getBitmapFromView(View view) {
view.buildDrawingCache();
Bitmap returnedBitmap = Bitmap.createBitmap(view.measuredWidth,
view.measuredHeight,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
canvas.drawColor(Color.WHITE, PorterDuff.Mode.SRC_IN);
Drawable drawable = view.background;
drawable.draw(canvas);
view.draw(canvas);
return returnedBitmap;
}
You'd also need to get the absolute location of the views:
Point getViewLocationOnScreen(View v) {
int[] coor = new int[]{0, 0};
v.getLocationOnScreen(coor);
return new Point(coor[0], coor[1]);
}
Then you just have to iterate through the pixels of each Bitmap, check their colors to know whether they're "filled", and also check whether they're overlapping based on their coordination inside the bitmaps and the absolute location of the views on screen.
Iterating through a bitmap's is done like this:
for (int x = 0; x < myBitmap.getWidth(); x++) {
for (int y = 0; y < myBitmap.getHeight(); y++) {
int color = myBitmap.getPixel(x, y);
}
}
But I must say, I don't think performing this sort of heavy computations on UI thread is really a good idea. There are dozens of much better ways to detect collisions than pixel-perfect checking. This will probably come out extremely laggy.
Related
For my game Hashi I want to build a custom ViewGroup that allows zooming and scrolling (both axes), containing children that are affected on touches as well.
I have set setWillNotDraw(false) and overwritten draw(Canvas) to use canvas.scale(..) and canvas.translate(..):
#Override
public void draw(Canvas canvas)
{
canvas.save();
canvas.scale(mScaleFactor, mScaleFactor, mScaleCenter.x, mScaleCenter.y);
canvas.translate(mTranslation.x * mScaleFactor, mTranslation.y * mScaleFactor);
super.draw(canvas);
canvas.restore();
}
But then I realized, that the MotionEvent parameter of the onTouchEvent for children is offset by the value I set with the translation (so they are detected, as if the container did not have any zoom or offset).
I tried to overwrite dispatchTouchEvent in the parent ViewGroup and adjust the coordinates of the event. But MotionEvent is final and can only be instantiated via MotionEvent.obtain(..). And there is no version of obtain to accept multiple coordinates, when there is more than one finger down.
Is there any way to modify the MotionEvent parameters, so I don't need to do it in the onTouchEvent methods of the child views (that would be much more complex), or even a better approach to implement zoom and scroll?
I implemented my own zoom container because I need to control the touches strictly (children also listen to swipe gestures, but need to be intercepted, when a second finger is down).
Don't try and create a new MotionEvent by providing coordinates.
Copy the existing event and then transform it using a matrix.
e.g. something like
// Matrix used for drawing the view
Matrix matrix = new Matrix();
matrix.setScale(scaleFactor, scaleFactor);
matrix.postTranslate(panX, panY);
// used with canvas.concat(matrix);
// Matrix for Touch events
Matrix mappingMatrix = new Matrix();
// Touch event matrix needs to be inverted
matrix.invert(mappingMatrix);
// Copy the touch Event that is being mapped
MotionEvent transformEvent = MotionEvent.obtain(ev);
// Apply it's event mapping matrix
transformEvent.transform(mappingMatrix);
Obtain copy documentation
I do something very similar in my custom viewgroup for scaling MotionEvents to children in my FixedHeaderTableLayout Library.
The MotionEvent copying is done here
So for those having the same problem I post my solution (thanks again Andrew for your help).
Update
Because I experienced input issues while testing, I decided to use onLayout instead of dispatchTouchEvent and draw methods to apply scale factor and translation, as the old solution did only apply it to the drawing and the input detection, but the container still declared the position of the children in the original place. This was causing espresso to execute the touches in the wrong place. With this solution the children are completely offset, so it also works with testing (and probably other things I did not consider).
Note that both solutions only work, when you embed (an) other layout container(s) that match the parents size.
If you want to change that, you need to change the implementation of onLayout.
public class ZoomContainer extends ViewGroup
{
/**
* Limit the maximum/minimum scrolling to prevent scrolling the container,
* so that no more children are visible.
* The value is relative to the size of the container (so 0.1 means 10% of the size of this container)
*/
protected float mTranslationBounds = 0.1f;
/**
* The translation to be applied to the container
*/
protected PointF mTranslation;
/**
* The the current zoom factor.
* It is initialized with a value smaller than 1, to append some empty space around the view.
*/
protected float mScaleFactor = 0.95f;
/**
* The minimum scale factor to prevent endless zooming
*/
protected float mScaleFactorMin = 0.8f;
/**
* The maximum scale factor to prevent endless zooming.
*/
protected float mScaleFactorMax = 5.0f;
/**
* Used to indicate, whether or not this is the first touch event, which has no differences yet.
*/
protected boolean mIsTouchStarted = false;
/**
* Distance of the fingers from the last touch event
*/
protected float mStartDistance = 0;
/**
* Center of the two fingers from the last touch event.
*/
protected PointF mStartTouchPoint = new PointF(0, 0);
public ZoomContainer(Context context)
{
super(context);
}
public ZoomContainer(Context context, #Nullable AttributeSet attrs)
{
super(context, attrs);
}
public ZoomContainer(Context context, #Nullable AttributeSet attrs, int defStyleAttr)
{
super(context, attrs, defStyleAttr);
}
/**
* Cancel all child touch events, if there is more than one finger down.
*/
#Override
public boolean onInterceptTouchEvent(MotionEvent ev)
{
boolean intercept = ev.getPointerCount() > 1;
if (intercept)
{
Log.d("TableView", "Intercepted");
mIsTouchStarted = false;
}
return intercept;
}
protected void initializeTranslation()
{
if (mTranslation == null)
{
mTranslation = new PointF(getWidth() * (1 - mScaleFactor) / 2f,
getHeight() * (1 - mScaleFactor) / 2f);
Log.d("TableView", "Translation: " + mTranslation);
}
}
/**
* Calculate the new zoom and scroll respecting the difference to the last touch event.
*/
#Override
public boolean onTouchEvent(MotionEvent event)
{
switch (event.getAction())
{
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
mIsTouchStarted = false;
return true;
}
if (event.getPointerCount() <= 1)
{
mIsTouchStarted = false;
return true;
}
float[] currentPointArray = new float[]{event.getX(0),
event.getY(0),
event.getX(1),
event.getY(1)};
float currentFingerDistance = getDistance(currentPointArray[0],
currentPointArray[1],
currentPointArray[2],
currentPointArray[3]);
// Read the current center of the fingers to determine the the new translation
PointF currentPoint = getPoint(currentPointArray[0],
currentPointArray[1],
currentPointArray[2],
currentPointArray[3]);
if (mIsTouchStarted)
{
// 1 / oldScaleFactor - 1 / newScaleFactor is required to respect the relative translation,
// when zooming (translation is always from the upper left corner,
// but zooming should be performed centered to the fingers)
float scaleFactorDifference = 1f / mScaleFactor;
mScaleFactor = getBoundScaleFactor(mScaleFactor + (currentFingerDistance / mStartDistance - 1));
scaleFactorDifference -= 1f / mScaleFactor;
// Add the finger scroll since the last event to the current translation.
PointF newTranslation = new PointF(mTranslation.x + (currentPoint.x - mStartTouchPoint.x) / mScaleFactor,
mTranslation.y + (currentPoint.y - mStartTouchPoint.y) / mScaleFactor);
// Add the current point multiplied with the scale difference to make sure,
// zooming is always done from the center of the fingers. Otherwise zooming would always be
// applied from the upper left edge of the screen.
newTranslation.x -= currentPoint.x * scaleFactorDifference;
newTranslation.y -= currentPoint.y * scaleFactorDifference;
mTranslation = getBoundTranslation(newTranslation);
}
mStartTouchPoint = currentPoint;
mStartDistance = currentFingerDistance;
mIsTouchStarted = true;
requestLayout();
return true;
}
protected float getBoundValue(float value, float min, float max)
{
return Math.min(Math.max(value, min), max);
}
protected PointF getBoundTranslation(PointF translation)
{
translation.x = getBoundValue(translation.x,
-(getWidth() * (mScaleFactor - 1) + getWidth() * mTranslationBounds),
getWidth() * mTranslationBounds);
translation.y = getBoundValue(translation.y,
-(getHeight() * (mScaleFactor - 1) + getHeight() * mTranslationBounds),
getHeight() * mTranslationBounds);
return translation;
}
protected float getBoundScaleFactor(float scaleFactor)
{
return getBoundValue(scaleFactor, mScaleFactorMin, mScaleFactorMax);
}
protected PointF getPoint(float x1, float y1, float x2, float y2)
{
return new PointF(getCenter(x1, x2), getCenter(y1, y2));
}
protected float getCenter(float position1, float position2)
{
return (position1 + position2) / 2f;
}
protected float getDistance(float x1, float y1, float x2, float y2)
{
float distanceX = Math.abs(x1 - x2);
float distanceY = Math.abs(y1 - y2);
return (float) Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2));
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b)
{
float width = (r - l);
float height = (b - t);
if (width <= 0 || height <= 0)
{
return;
}
initializeTranslation();
final int childCount = getChildCount();
l = (int) (mTranslation.x * mScaleFactor);
r = (int) ((width + mTranslation.x) * mScaleFactor);
t = (int) (mTranslation.y * mScaleFactor);
b = (int) ((height + mTranslation.y) * mScaleFactor);
for (int i = 0; i < childCount; i++)
{
View child = getChildAt(i);
child.layout(l, t, r, b);
}
}
}
Old solution
Using dispatchTouchEvent and draw methods to apply scale factor and tranlation:
public class ZoomContainer extends ViewGroup
{
/**
* Limit the maximum/minimum scrolling to prevent scrolling the container,
* so that no more children are visible.
* The value is relative to the size of the container (so 0.1 means 10% of the size of this container)
*/
protected float mTranslationBounds = 0.1f;
/**
* The translation to be applyed to the container
*/
protected PointF mTranslation;
/**
* The the current zoom factor. You might initialze it to a value smaller than 1, if you want to add some padding in the beginning.
*/
protected float mScaleFactor = 1f;
/**
* The minimum scale factor to prevent endless zooming
*/
protected float mScaleFactorMin = 0.8f;
/**
* The maximum scale factor to prevent endless zooming.
*/
protected float mScaleFactorMax = 4f;
/**
* Used to indicate, whether or not this is the first touch event, which has no differences yet.
*/
protected boolean mIsTouchStarted = false;
/**
* Distance of the fingers from the last touch event
*/
protected float mStartDistance = 0;
/**
* Center of the two fingers from the last touch event.
*/
protected PointF mStartTouchPoint = new PointF(0, 0);
public ZoomContainer(Context context)
{
super(context);
setWillNotDraw(false);
}
public ZoomContainer(Context context, #Nullable AttributeSet attrs)
{
super(context, attrs);
setWillNotDraw(false);
}
public ZoomContainer(Context context, #Nullable AttributeSet attrs, int defStyleAttr)
{
super(context, attrs, defStyleAttr);
setWillNotDraw(false);
}
#Override
public void draw(Canvas canvas)
{
canvas.save();
canvas.concat(createDrawMatrix());
super.draw(canvas);
canvas.restore();
}
/**
* Cancel all child touch events, if there is more than one finger down.
*/
#Override
public boolean onInterceptTouchEvent(MotionEvent ev)
{
boolean intercept = ev.getPointerCount() > 1;
if (intercept)
{
mIsTouchStarted = false;
}
return intercept;
}
/**
* Creates the transformation matrix for drawing and converting touch coordinates
*/
protected Matrix createDrawMatrix()
{
// Make sure children are centered, if initial scroll factor is not 1.
if (mTranslation == null)
{
mTranslation = new PointF(getWidth() * (1 - mScaleFactor) / 2f,
getHeight() * (1 - mScaleFactor) / 2f);
}
// Matrix used for drawing the view
Matrix matrix = new Matrix();
matrix.setScale(mScaleFactor, mScaleFactor);
matrix.postTranslate(mTranslation.x, mTranslation.y);
return matrix;
}
/**
* Transform the touch coordinates according to the current zoom and scroll,
* for children to get the appropriate ones.
*/
#Override
public boolean dispatchTouchEvent(MotionEvent ev)
{
// Matrix for Touch events
Matrix mappingMatrix = new Matrix();
// Touch event matrix needs to be inverted
createDrawMatrix().invert(mappingMatrix);
// Copy the touch Event that is being mapped
MotionEvent transformEvent = MotionEvent.obtain(ev);
// Apply it's event mapping matrix
transformEvent.transform(mappingMatrix);
boolean handled = super.dispatchTouchEvent(transformEvent);
transformEvent.recycle();
return handled;
}
/**
* Calculate the new zoom and scroll respecting the difference to the last touch event.
*/
#Override
public boolean onTouchEvent(MotionEvent event)
{
switch (event.getAction())
{
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
mIsTouchStarted = false;
return true;
}
//
if (event.getPointerCount() <= 1)
{
mIsTouchStarted = false;
return true;
}
float[] currentPointArray = new float[]{event.getX(0),
event.getY(0),
event.getX(1),
event.getY(1)};
float currentDistance = mScaleFactor * getDistance(currentPointArray[0],
currentPointArray[1],
currentPointArray[2],
currentPointArray[3]);
Matrix transformation = createDrawMatrix();
transformation.mapPoints(currentPointArray);
PointF currentPoint = getPoint(currentPointArray[0],
currentPointArray[1],
currentPointArray[2],
currentPointArray[3]);
if (mIsTouchStarted)
{
float scaleFactorDifference = mScaleFactor;
mScaleFactor = getBoundScaleFactor(mScaleFactor + (currentDistance / mStartDistance - 1));
scaleFactorDifference -= mScaleFactor;
PointF newTranslation = new PointF(mTranslation.x + currentPoint.x - mStartTouchPoint.x,
mTranslation.y + currentPoint.y - mStartTouchPoint.y);
newTranslation.x += currentPoint.x * scaleFactorDifference;
newTranslation.y += currentPoint.y * scaleFactorDifference;
mTranslation = getBoundTranslation(newTranslation);
}
mStartTouchPoint = currentPoint;
mStartDistance = currentDistance;
mIsTouchStarted = true;
invalidate();
return true;
}
protected float getBoundValue(float value, float min, float max)
{
return Math.min(Math.max(value, min), max);
}
protected PointF getBoundTranslation(PointF translation)
{
translation.x = getBoundValue(translation.x,
-(getWidth() * (mScaleFactor - 1) + getWidth() * mTranslationBounds),
getWidth() * mTranslationBounds);
translation.y = getBoundValue(translation.y,
-(getHeight() * (mScaleFactor - 1) + getHeight() * mTranslationBounds),
getHeight() * mTranslationBounds);
return translation;
}
protected float getBoundScaleFactor(float scaleFactor)
{
return getBoundValue(scaleFactor, mScaleFactorMin, mScaleFactorMax);
}
protected PointF getPoint(float x1, float y1, float x2, float y2)
{
return new PointF(getCenter(x1, x2), getCenter(y1, y2));
}
protected float getCenter(float position1, float position2)
{
return (position1 + position2) / 2f;
}
protected float getDistance(float x1, float y1, float x2, float y2)
{
float distanceX = Math.abs(x1 - x2);
float distanceY = Math.abs(y1 - y2);
return (float) Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2));
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b)
{
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++)
{
View child = getChildAt(i);
child.layout(0, 0, r - l, b - t);
}
}
}
I'm working with an android studio project. I'm trying to select user touched pixel on an image, as shown Fig 1.
I want to add (X) on a pixel touched by the user, how can I make it by modifying bitmap ?
This is image.
If I understand your question correctly, you want to draw X in each time the user click on Bitmap, here's what you need :
ImageView img;
int clickCount = 0;
Bitmap src;
int colorTarget = Color.BLACK;
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = findViewById(R.id.img);
img.setOnTouchListener((v, event) -> {
int x = (int) event.getX();
int y = (int) event.getY();
if (event.getAction() == MotionEvent.ACTION_DOWN) {
drawXByPosition(img, src, x, y);
} else if (event.getAction() == MotionEvent.ACTION_UP) {
clickCount++;
if (clickCount % 2 == 0) colorTarget = Color.BLACK;
else colorTarget = Color.WHITE;
}
return true;
});
}
private void drawXByPosition(ImageView iv, Bitmap bm, int x, int y) {
if (x < 0 || y < 0 || x > iv.getWidth() || y > iv.getHeight())
Toast.makeText(getApplicationContext(), "Outside of ImageView", Toast.LENGTH_SHORT).show();
else {
int projectedX = (int) ((double) x * ((double) bm.getWidth() / (double) iv.getWidth()));
int projectedY = (int) ((double) y * ((double) bm.getHeight() / (double) iv.getHeight()));
src = drawX(src, "X", 44, colorTarget, projectedX, projectedY);
img.setImageBitmap(src);
}
}
public Bitmap drawX(final Bitmap src,
final String content,
final float textSize,
#ColorInt final int color,
final float x,
final float y) {
Bitmap ret = src.copy(src.getConfig(), true);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
Canvas canvas = new Canvas(ret);
paint.setColor(color);
paint.setTextSize(textSize);
Rect bounds = new Rect();
paint.getTextBounds(content, 0, content.length(), bounds);
canvas.drawText(content, x, y + textSize, paint);
return ret;
}
I want to do a "zoomable paint", I mean a paint that I can zoom/zoom out and pan/drag the canvas and then draw on it.
I have a problem that I can't solve: when I draw while the canvas is zoomed, I retrieve the X and Y coordinate and effectively drawing it on the canvas. But these coordinates are not correct because of the zoomed canvas.
I tried to correct these (multiply by (zoomHeigh/screenHeight)) but I can't find a way to retrieve where I must draw on the original/none-zoomed screen
This is my code :
public class PaintView extends View {
public static int BRUSH_SIZE = 20;
public static final int DEFAULT_COLOR = Color.BLACK;
public static final int DEFAULT_BG_COLOR = Color.WHITE;
private static final float TOUCH_TOLERANCE = 4;
private float mX, mY;
private SerializablePath mPath;
private Paint mPaint;
private ArrayList<FingerPath> paths = new ArrayList<>();
private ArrayList<FingerPath> tempPaths = new ArrayList<>();
private int currentColor;
private int backgroundColor = DEFAULT_BG_COLOR;
private int strokeWidth;
private boolean emboss;
private boolean blur;
private boolean eraser;
private MaskFilter mEmboss;
private MaskFilter mBlur;
private Bitmap mBitmap;
private Canvas mCanvas;
private Paint mBitmapPaint = new Paint(Paint.DITHER_FLAG);
public boolean zoomViewActivated = false;
//These two constants specify the minimum and maximum zoom
private static float MIN_ZOOM = 1f;
private static float MAX_ZOOM = 5f;
private float scaleFactor = 1.f;
private ScaleGestureDetector detector;
//These constants specify the mode that we're in
private static int NONE = 0;
private static int DRAG = 1;
private static int ZOOM = 2;
private int mode;
//These two variables keep track of the X and Y coordinate of the finger when it first
//touches the screen
private float startX = 0f;
private float startY = 0f;
//These two variables keep track of the amount we need to translate the canvas along the X
//and the Y coordinate
private float translateX = 0f;
private float translateY = 0f;
//These two variables keep track of the amount we translated the X and Y coordinates, the last time we
//panned.
private float previousTranslateX = 0f;
private float previousTranslateY = 0f;
int currentPositionX = 0;
int currentPositionY = 0;
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScale(ScaleGestureDetector detector) {
scaleFactor *= detector.getScaleFactor();
scaleFactor = Math.max(MIN_ZOOM, Math.min(scaleFactor, MAX_ZOOM));
return true;
}
}
public ArrayList<FingerPath> getDividedPaths(float i){
for(FingerPath p : this.paths){
Matrix scaleMatrix = new Matrix();
scaleMatrix.setScale(i, i);
p.path.transform(scaleMatrix);
}
return this.paths;
}
public ArrayList<FingerPath> getPaths() {
return paths;
}
public void dividePath(float i) {
for(FingerPath p : this.paths){
Matrix scaleMatrix = new Matrix();
scaleMatrix.setScale(i, i);
p.path.transform(scaleMatrix);
}
}
public void setPaths(ArrayList<FingerPath> paths){
this.paths = paths;
}
public void setStrokeWidth(int value){
strokeWidth = value;
}
public PaintView(Context context) {
this(context, null);
detector = new ScaleGestureDetector(getContext(), new ScaleListener());
}
public PaintView(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(DEFAULT_COLOR);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setXfermode(null);
mPaint.setAlpha(0xff);
mEmboss = new EmbossMaskFilter(new float[] {1, 1, 1}, 0.4f, 6, 3.5f);
mBlur = new BlurMaskFilter(5, BlurMaskFilter.Blur.NORMAL);
detector = new ScaleGestureDetector(getContext(), new ScaleListener());
}
public void init(DisplayMetrics metrics) {
int height = metrics.heightPixels;
int width = metrics.widthPixels;
mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
currentColor = DEFAULT_COLOR;
strokeWidth = BRUSH_SIZE;
}
public void normal() {
emboss = false;
blur = false;
eraser = false;
}
public void emboss() {
emboss = true;
blur = false;
eraser = false;
}
public void blur() {
emboss = false;
blur = true;
eraser = false;
}
public void eraser() {
eraser = true;
}
public void cancel(){
if(paths.size() != 0){
tempPaths.add(paths.get(paths.size()-1));
paths.remove(paths.size()-1);
invalidate();
}
}
public void redo(){
if(tempPaths.size() != 0){
paths.add(tempPaths.get(tempPaths.size()-1));
tempPaths.remove(tempPaths.size()-1);
invalidate();
}
}
public void clear() {
backgroundColor = DEFAULT_BG_COLOR;
paths.clear();
normal();
invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.save();
//We're going to scale the X and Y coordinates by the same amount
canvas.scale(scaleFactor, scaleFactor);
//If translateX times -1 is lesser than zero, let's set it to zero. This takes care of the left bound
if((translateX * -1) < 0) {
translateX = 0;
}
//This is where we take care of the right bound. We compare translateX times -1 to (scaleFactor - 1) * displayWidth.
//If translateX is greater than that value, then we know that we've gone over the bound. So we set the value of
//translateX to (1 - scaleFactor) times the display width. Notice that the terms are interchanged; it's the same
//as doing -1 * (scaleFactor - 1) * displayWidth
else if((translateX * -1) > (scaleFactor - 1) * getWidth()) {
translateX = (1 - scaleFactor) * getWidth();
}
if(translateY * -1 < 0) {
translateY = 0;
}
//We do the exact same thing for the bottom bound, except in this case we use the height of the display
else if((translateY * -1) > (scaleFactor - 1) * getHeight()) {
translateY = (1 - scaleFactor) * getHeight();
}
//We need to divide by the scale factor here, otherwise we end up with excessive panning based on our zoom level
//because the translation amount also gets scaled according to how much we've zoomed into the canvas.
canvas.translate(translateX / scaleFactor, translateY / scaleFactor);
/* The rest of your canvas-drawing code */
mCanvas.drawColor(backgroundColor);
if(paths != null){
for (FingerPath fp : paths) {
mPaint.setColor(fp.color);
mPaint.setStrokeWidth(fp.strokeWidth);
mPaint.setMaskFilter(null);
if (fp.emboss)
mPaint.setMaskFilter(mEmboss);
else if (fp.blur)
mPaint.setMaskFilter(mBlur);
if(fp.eraser) {
mPaint.setColor(DEFAULT_BG_COLOR);
}
mCanvas.drawPath(fp.path, mPaint);
}
}
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.restore();
}
private void touchStart(float x, float y) {
mPath = new SerializablePath();
FingerPath fp = new FingerPath(currentColor, emboss, blur, eraser, strokeWidth, mPath);
paths.add(fp);
tempPaths = new ArrayList<>();
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
}
private void touchMove(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 touchUp() {
mPath.lineTo(mX, mY);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if(zoomViewActivated){
boolean dragged = false;
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
mode = DRAG;
//We assign the current X and Y coordinate of the finger to startX and startY minus the previously translated
//amount for each coordinates This works even when we are translating the first time because the initial
//values for these two variables is zero.
startX = event.getX() - previousTranslateX;
startY = event.getY() - previousTranslateY;
break;
case MotionEvent.ACTION_MOVE:
translateX = event.getX() - startX;
translateY = event.getY() - startY;
//We cannot use startX and startY directly because we have adjusted their values using the previous translation values.
//This is why we need to add those values to startX and startY so that we can get the actual coordinates of the finger.
double distance = Math.sqrt(Math.pow(event.getX() - (startX + previousTranslateX), 2) +
Math.pow(event.getY() - (startY + previousTranslateY), 2)
);
if(distance > 0) {
dragged = true;
}
break;
case MotionEvent.ACTION_POINTER_DOWN:
mode = ZOOM;
break;
case MotionEvent.ACTION_UP:
mode = NONE;
dragged = false;
//All fingers went up, so let's save the value of translateX and translateY into previousTranslateX and
//previousTranslate
previousTranslateX = translateX;
previousTranslateY = translateY;
currentPositionX += previousTranslateX;
currentPositionY += previousTranslateY;
break;
case MotionEvent.ACTION_POINTER_UP:
mode = DRAG;
//This is not strictly necessary; we save the value of translateX and translateY into previousTranslateX
//and previousTranslateY when the second finger goes up
previousTranslateX = translateX;
previousTranslateY = translateY;
break;
}
detector.onTouchEvent(event);
//We redraw the canvas only in the following cases:
//
// o The mode is ZOOM
// OR
// o The mode is DRAG and the scale factor is not equal to 1 (meaning we have zoomed) and dragged is
// set to true (meaning the finger has actually moved)
if ((mode == DRAG && scaleFactor != 1f && dragged) || mode == ZOOM) {
invalidate();
}
}else{
float x = event.getX()*(getHeight()/scaleFactor)/getHeight()+currentPositionX;
float y = event.getY()*(getWidth()/scaleFactor)/getWidth()+currentPositionY;
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN :
touchStart(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE :
touchMove(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP :
touchUp();
invalidate();
break;
}
}
return true;
}
}
I'm new in Android programming, and I've tried to write a simple app recently, just for practice! In this one, I want to color an image on user's tap, but I don't know how to start it. I've read different topics which say to use the "Flood Fill" algorithm. I've found it on the web, but I don't know how to put it into my simple app.
The code I've found:
private void FloodFill(Bitmap bmp, Point pt, int targetColor, int replacementColor)
{
Queue<Point> q = new LinkedList<Point>();
q.add(pt);
while (q.size() > 0) {
Point n = q.poll();
if (bmp.getPixel(n.x, n.y) != targetColor)
continue;
Point w = n, e = new Point(n.x + 1, n.y);
while ((w.x > 0) && (bmp.getPixel(w.x, w.y) == targetColor)) {
bmp.setPixel(w.x, w.y, replacementColor);
if ((w.y > 0) && (bmp.getPixel(w.x, w.y - 1) == targetColor))
q.add(new Point(w.x, w.y - 1));
if ((w.y < bmp.getHeight() - 1) && (bmp.getPixel(w.x, w.y + 1) == targetColor))
q.add(new Point(w.x, w.y + 1));
w.x--;
}
while ((e.x < bmp.getWidth() - 1) && (bmp.getPixel(e.x, e.y) == targetColor)) {
bmp.setPixel(e.x, e.y, replacementColor);
if ((e.y > 0) && (bmp.getPixel(e.x, e.y - 1) == targetColor))
q.add(new Point(e.x, e.y - 1));
if ((e.y < bmp.getHeight() - 1) && (bmp.getPixel(e.x, e.y + 1) == targetColor))
q.add(new Point(e.x, e.y + 1));
e.x++;
}
}
}
I know how to draw lines on the screen following user's finger on touch event, but I'd also like to know how to fill a given image with some color, for example this one:
A little lion!
I saw these other questions on stack overflow:
First topic
Second topic
Third topic
It seems so easy to do, but I can't! Can you show me a little example please? I'd like to know how to set the canvas, the image to color, and how to do it.
android using flood fill algorithm getting out of memory exception. Check the link has an example.
You need the the co-ordinates of x and y touch and you can use asynctask to floofill a closed area. Use a progressdialog untill the floodfill fills the closed area with replacement color.
Note: I have faced problem when coloring large closed are. It took lot of time. I am not sure if using asynctask is the beast way. I hope someone can clarify on that part
You can modify the below according to your needs.
final Point p1 = new Point();
p1.x=(int) x; //x co-ordinate where the user touches on the screen
p1.y=(int) y; //y co-ordinate where the user touches on the screen
FloodFill f= new FloodFill();
f.floodFill(bmp,pt,targetColor,replacementColor);
FloodFill algorithm to fill a closed area
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);
}
}
}
Edit:
Edit 8-7-2014 :
Filling a small closed area works fine with the above flood fill algorithm. However for large area the algorithm works slow and consumes lot of memory. Recently i came across a post which uses QueueLinear Flood Fill which is way faster that the above.
Source :
http://www.codeproject.com/Articles/16405/Queue-Linear-Flood-Fill-A-Fast-Flood-Fill-Algorith
Code :
public class QueueLinearFloodFiller {
protected Bitmap image = null;
protected int[] tolerance = new int[] { 0, 0, 0 };
protected int width = 0;
protected int height = 0;
protected int[] pixels = null;
protected int fillColor = 0;
protected int[] startColor = new int[] { 0, 0, 0 };
protected boolean[] pixelsChecked;
protected Queue<FloodFillRange> ranges;
// Construct using an image and a copy will be made to fill into,
// Construct with BufferedImage and flood fill will write directly to
// provided BufferedImage
public QueueLinearFloodFiller(Bitmap img) {
copyImage(img);
}
public QueueLinearFloodFiller(Bitmap img, int targetColor, int newColor) {
useImage(img);
setFillColor(newColor);
setTargetColor(targetColor);
}
public void setTargetColor(int targetColor) {
startColor[0] = Color.red(targetColor);
startColor[1] = Color.green(targetColor);
startColor[2] = Color.blue(targetColor);
}
public int getFillColor() {
return fillColor;
}
public void setFillColor(int value) {
fillColor = value;
}
public int[] getTolerance() {
return tolerance;
}
public void setTolerance(int[] value) {
tolerance = value;
}
public void setTolerance(int value) {
tolerance = new int[] { value, value, value };
}
public Bitmap getImage() {
return image;
}
public void copyImage(Bitmap img) {
// Copy data from provided Image to a BufferedImage to write flood fill
// to, use getImage to retrieve
// cache data in member variables to decrease overhead of property calls
width = img.getWidth();
height = img.getHeight();
image = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(image);
canvas.drawBitmap(img, 0, 0, null);
pixels = new int[width * height];
image.getPixels(pixels, 0, width, 1, 1, width - 1, height - 1);
}
public void useImage(Bitmap img) {
// Use a pre-existing provided BufferedImage and write directly to it
// cache data in member variables to decrease overhead of property calls
width = img.getWidth();
height = img.getHeight();
image = img;
pixels = new int[width * height];
image.getPixels(pixels, 0, width, 1, 1, width - 1, height - 1);
}
protected void prepare() {
// Called before starting flood-fill
pixelsChecked = new boolean[pixels.length];
ranges = new LinkedList<FloodFillRange>();
}
// Fills the specified point on the bitmap with the currently selected fill
// color.
// int x, int y: The starting coords for the fill
public void floodFill(int x, int y) {
// Setup
prepare();
if (startColor[0] == 0) {
// ***Get starting color.
int startPixel = pixels[(width * y) + x];
startColor[0] = (startPixel >> 16) & 0xff;
startColor[1] = (startPixel >> 8) & 0xff;
startColor[2] = startPixel & 0xff;
}
// ***Do first call to floodfill.
LinearFill(x, y);
// ***Call floodfill routine while floodfill ranges still exist on the
// queue
FloodFillRange range;
while (ranges.size() > 0) {
// **Get Next Range Off the Queue
range = ranges.remove();
// **Check Above and Below Each Pixel in the Floodfill Range
int downPxIdx = (width * (range.Y + 1)) + range.startX;
int upPxIdx = (width * (range.Y - 1)) + range.startX;
int upY = range.Y - 1;// so we can pass the y coord by ref
int downY = range.Y + 1;
for (int i = range.startX; i <= range.endX; i++) {
// *Start Fill Upwards
// if we're not above the top of the bitmap and the pixel above
// this one is within the color tolerance
if (range.Y > 0 && (!pixelsChecked[upPxIdx])
&& CheckPixel(upPxIdx))
LinearFill(i, upY);
// *Start Fill Downwards
// if we're not below the bottom of the bitmap and the pixel
// below this one is within the color tolerance
if (range.Y < (height - 1) && (!pixelsChecked[downPxIdx])
&& CheckPixel(downPxIdx))
LinearFill(i, downY);
downPxIdx++;
upPxIdx++;
}
}
image.setPixels(pixels, 0, width, 1, 1, width - 1, height - 1);
}
// Finds the furthermost left and right boundaries of the fill area
// on a given y coordinate, starting from a given x coordinate, filling as
// it goes.
// Adds the resulting horizontal range to the queue of floodfill ranges,
// to be processed in the main loop.
// int x, int y: The starting coords
protected void LinearFill(int x, int y) {
// ***Find Left Edge of Color Area
int lFillLoc = x; // the location to check/fill on the left
int pxIdx = (width * y) + x;
while (true) {
// **fill with the color
pixels[pxIdx] = fillColor;
// **indicate that this pixel has already been checked and filled
pixelsChecked[pxIdx] = true;
// **de-increment
lFillLoc--; // de-increment counter
pxIdx--; // de-increment pixel index
// **exit loop if we're at edge of bitmap or color area
if (lFillLoc < 0 || (pixelsChecked[pxIdx]) || !CheckPixel(pxIdx)) {
break;
}
}
lFillLoc++;
// ***Find Right Edge of Color Area
int rFillLoc = x; // the location to check/fill on the left
pxIdx = (width * y) + x;
while (true) {
// **fill with the color
pixels[pxIdx] = fillColor;
// **indicate that this pixel has already been checked and filled
pixelsChecked[pxIdx] = true;
// **increment
rFillLoc++; // increment counter
pxIdx++; // increment pixel index
// **exit loop if we're at edge of bitmap or color area
if (rFillLoc >= width || pixelsChecked[pxIdx] || !CheckPixel(pxIdx)) {
break;
}
}
rFillLoc--;
// add range to queue
FloodFillRange r = new FloodFillRange(lFillLoc, rFillLoc, y);
ranges.offer(r);
}
// Sees if a pixel is within the color tolerance range.
protected boolean CheckPixel(int px) {
int red = (pixels[px] >>> 16) & 0xff;
int green = (pixels[px] >>> 8) & 0xff;
int blue = pixels[px] & 0xff;
return (red >= (startColor[0] - tolerance[0])
&& red <= (startColor[0] + tolerance[0])
&& green >= (startColor[1] - tolerance[1])
&& green <= (startColor[1] + tolerance[1])
&& blue >= (startColor[2] - tolerance[2]) && blue <= (startColor[2] + tolerance[2]));
}
// Represents a linear range to be filled and branched from.
protected class FloodFillRange {
public int startX;
public int endX;
public int Y;
public FloodFillRange(int startX, int endX, int y) {
this.startX = startX;
this.endX = endX;
this.Y = y;
}
}
}
Thanks to the stackoverflow's users I've gotten to the right solution!
I wanted to know how to use the flood fill algorithm and integrate it in a simple Android project, and this is what I did:
Java code:
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.BitmapFactory.Options;
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);
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);
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);
}
}
}
}
And this is the XML code:
<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"
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" >
</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>
I hope it to be helpfull for you!!!
Have a nice day!!!
How could I smoothly create a zoom animation for a canvas?
GWT provides a onMouseWheel(MouseWheelEvent evt) method and a evt.getDeltaY() to get the amount of scroll wheel.
Problem here is, that every wheel movement executes this method, and if I call a canvas redraw in the method itself, things get very laggy.
So I thought of somehow making an animation for the zooming. But how?
I thought about creating a Timer, but have no real idea, as there is only the mousewheelevent as starting point, but no end point that the user finished zooming with the wheel...
Here is my scalable image class that I use to zoom into images, it is very quick and responsive. I found an example somewhere and made some minor modifications to make it more responsive. I don't remember the original source or I would give them credit here.
public class ScalableImage extends Composite implements MouseWheelHandler, MouseDownHandler, MouseMoveHandler, MouseUpHandler {
Canvas canvas = Canvas.createIfSupported();
Context2d context = canvas.getContext2d();
Canvas backCanvas = Canvas.createIfSupported();
Context2d backContext = backCanvas.getContext2d();
int width;
int height;
Image image;
ImageElement imageElement;
double zoom = 1;
double totalZoom = 1;
double offsetX = 0;
double offsetY = 0;
boolean mouseDown = false;
double mouseDownXPos = 0;
double mouseDownYPos = 0;
public ScalableImage(Image image) {
initWidget(canvas);
//width = Window.getClientWidth() - 50;
width = image.getWidth() + 200;
height = image.getHeight() + 200;
//canvas.setWidth(width + "px");
//canvas.setHeight(height + "px");
canvas.setCoordinateSpaceWidth(width);
canvas.setCoordinateSpaceHeight(height);
//backCanvas.setWidth(width + "px");
//backCanvas.setHeight(height + "px");
backCanvas.setCoordinateSpaceWidth(width);
backCanvas.setCoordinateSpaceHeight(height);
canvas.addMouseWheelHandler(this);
canvas.addMouseMoveHandler(this);
canvas.addMouseDownHandler(this);
canvas.addMouseUpHandler(this);
this.image = image;
this.imageElement = (ImageElement) image.getElement().cast();
mainDraw();
}
public void onMouseWheel(MouseWheelEvent event) {
int move = event.getDeltaY();
double xPos = (event.getRelativeX(canvas.getElement()));
double yPos = (event.getRelativeY(canvas.getElement()));
if (move < 0) {
zoom = 1.1;
} else {
zoom = 1 / 1.1;
}
double newX = (xPos - offsetX) / totalZoom;
double newY = (yPos - offsetY) / totalZoom;
double xPosition = (-newX * zoom) + newX;
double yPosition = (-newY * zoom) + newY;
backContext.clearRect(0, 0, width, height);
backContext.translate(xPosition, yPosition);
backContext.scale(zoom, zoom);
mainDraw();
offsetX += (xPosition * totalZoom);
offsetY += (yPosition * totalZoom);
totalZoom = totalZoom * zoom;
buffer(backContext, context);
}
public void onMouseDown(MouseDownEvent event) {
this.mouseDown = true;
mouseDownXPos = event.getRelativeX(image.getElement());
mouseDownYPos = event.getRelativeY(image.getElement());
}
public void onMouseMove(MouseMoveEvent event) {
if (mouseDown) {
backContext.setFillStyle("white");
backContext.fillRect(-5, -5, width + 5, height + 5);
backContext.setFillStyle("black");
double xPos = event.getRelativeX(image.getElement());
double yPos = event.getRelativeY(image.getElement());
backContext.translate((xPos - mouseDownXPos) / totalZoom, (yPos - mouseDownYPos) / totalZoom);
offsetX += (xPos - mouseDownXPos);
offsetY += (yPos - mouseDownYPos);
mainDraw();
mouseDownXPos = xPos;
mouseDownYPos = yPos;
}
}
public void onMouseUp(MouseUpEvent event) {
this.mouseDown = false;
}
public void mainDraw() {
backContext.drawImage(imageElement, 100, 100);
buffer(backContext, context);
}
public void buffer(Context2d back, Context2d front) {
front.beginPath();
front.clearRect(0, 0, width, height);
front.drawImage(back.getCanvas(), 0, 0);
}
}