custom view can be clicked - android

I want to make my custom view be clicked.And now I do not know which is wrong,when I click it
,it happens nothing.Thanks in advance.This view is that I use canvas to draw a ring,and I want the inside of the ring can be clicked.
public class CircleProgressBar extends View{
OnClickListener progressButton;
private int hour;
private int maxProgress = 24;
private int progress;
int progress1;
private int progressStrokeWidth = 32;
RectF oval;
Paint paint;
Paint paint1;
public CircleProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
oval = new RectF();
paint = new Paint();
paint1 = new Paint();
}
#Override
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
Calendar c=Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
progress = hour;
int width = this.getWidth();
int height = this.getHeight();
if(width != height){
int min = Math.min(width, height);
width = min;
height = min;
}
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setColor(Color.LTGRAY);
canvas.drawColor(Color.TRANSPARENT);
paint.setStrokeWidth(15);
paint.setStyle(Style.STROKE);
oval.left = progressStrokeWidth / 2; // 左上角x
oval.top = progressStrokeWidth / 2; // 左上角y
oval.right =height - progressStrokeWidth / 2; // 左下角x
oval.bottom = height - progressStrokeWidth / 2; // 右下角y
canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG|Paint.FILTER_BITMAP_FLAG));
canvas.drawArc(oval, -90, 360, false, paint);
paint.setColor(Color.rgb(0x57, 0x87, 0xb6));
paint.setStrokeCap(Paint.Cap.ROUND);
if(progress == 9){
canvas.drawArc(oval, -90, 134, false, paint);
}else{
canvas.drawArc(oval, -90, (long)(((float) progress / maxProgress) * 360), false, paint);
}
paint.setColor(Color.CYAN);
paint.setAntiAlias(true);
canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG|Paint.FILTER_BITMAP_FLAG));
canvas.drawArc(oval, -90, 135+0.5f, false, paint);
paint.setStrokeWidth(15);
String text = (long)(((float) progress / maxProgress) * 100) + "%";
int textHeight = height / 4;
paint.setTextSize(textHeight);
int textWidth = (int) paint.measureText(text, 0, text.length());
paint.setStyle(Style.FILL);
canvas.drawText(text, width / 2 - textWidth / 2, height / 2 +textHeight/2, paint);
}
public int getMaxProgress() {
return maxProgress;
}
public void setMaxProgress(int maxProgress) {
this.maxProgress = maxProgress;
}
public void setProgress(int progress) {
this.progress = progress;
this.invalidate();
}
public void setProgressNotInUiThread(int progress) {
this.progress = progress;
this.postInvalidate();
}
#Override
public boolean onTouchEvent(MotionEvent event){
if(event.getAction() == MotionEvent.ACTION_DOWN){
}
return true;
}
This is my main activity.
public class MainActivity extends Activity{
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.circle_fit);
CircleProgressBar progressBar = (CircleProgressBar) findViewById(R.id.circleProgressbar);
progressBar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(MainActivity.this, "hello", Toast.LENGTH_SHORT).show();
}
});
here is my xml
<com.example.circlefit.CircleProgressBar
android:id="#+id/circleProgressbar"
android:layout_width="200dp"
android:layout_height="200dp" />

Remove the touch listener in your custom class. It is ovveriding the click functionality :-
/
/Remove this piece of code from your class and it will work just fine
#Override
public boolean onTouchEvent(MotionEvent event){
if(event.getAction() == MotionEvent.ACTION_DOWN){
}
return true;
}

Add this in your XML:
android:clickable="true"
android:focusable="true"

try like this:
private OnClickListener clickListener;
private boolean isMoved;
#Override
public void setOnClickListener(OnClickListener l) {
this.clickListener = l;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
isMoved = false;
if (isValidtouchAndIsInsideCircle(event)) {
return true;
} else {
return false;
}
}
if (event.getAction() == MotionEvent.ACTION_MOVE) {
isMoved = true;
}
if (event.getAction() == MotionEvent.ACTION_UP) {
if (clickListener != null && !isMoved) {
clickListener.onClick(this);
}
isMoved = false;
}
return false;
}
private boolean isValidtouchAndIsInsideCircle(MotionEvent event) {
int xPoint = (int) event.getX();
int yPoint = (int) event.getY();
// here validate the x and y points with your circle coordinates if it
// is in circle return true or else return false
return false;
}

Related

Setting border to circular imageview is not working when paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));

I want to set border to circular Image view and also want the image view to be inside the circle, so below is my code-
public static Bitmap getRoundedRectBitmap(Bitmap bitmap, int pixels) {
Bitmap result = null;
try {
result = Bitmap.createBitmap(pixels, pixels, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
Rect rect = new Rect(0, 0, pixels*2, pixels*2);
// paint.setAntiAlias(true);
//; canvas.drawARGB(0, 0, 0, 0);
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
canvas.drawCircle(pixels/2, pixels/2, pixels/2, paint);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(15);
paint.setColor(Color.parseColor("#17B3F0"));
canvas.drawCircle(pixels/2+0.7f, pixels/2+0.7f, pixels/2+0.1f, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
} catch (NullPointerException e) {
} catch (OutOfMemoryError o) {
}
return result;
}
So the problem is with the line
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
If I am commenting this line, it's making all the properties added to paint object visible but making image comes out of the circle.
But I want the Image to be inside the circle as well as a border to be set.
Any help is appreciated.Thanks.
Updated from Here -
I have created a custom class which MyCustomAdapter and Inside getView I am setting the imageView onStateChangeListener as below -
#Override
public View getView(int position, View convertView, ViewGroup parent) {
int type = getItemViewType(position);
View view = inflater.inflate(type == List_Section ? R.layout.section : R.layout.listitem, parent, false);
if (type == List_Section) {
departments = ((TextView) view.findViewById(R.id.tv_li_section));
departments.setText(list_complete_data.get(position).toString());
} else {
//StateListDrawable stateListDrawable = (StateListDrawable) view.getBackground();
Emp_name = (TextView) view.findViewById(R.id.emp_name);
Emp_number = (TextView) view.findViewById(R.id.emp_no);
small_profile =(CircleImageView)view.findViewById(R.id.small_profile);
Log.e(TAG,"small_profile====="+small_profile);
Log.e(TAG,"inside getView=====");
small_profile.setOnStateChangedListener(new OnStateChangeListener() {
#Override
public void onStateChanged(int state) {
Log.e(TAG,"onStateistener and state=="+state+".,,,R.attr.state_on==="+R.attr.state_on+",,,R.attr.state_off=="+R.attr.state_off);
switch (state){
case R.attr.state_on :
small_profile.setBorderColor(Color.parseColor("#ffffff"));
break;
case R.attr.state_off:
small_profile.setBorderColor(Color.parseColor("#000000"));
break;
}
}
});
EDIT : I have made some changes to the code according to your requirements:
add the following interface to your project:
public interface OnStateChangeListener {
void onStateChanged(int state);
}
and then make then I made some changes in the CircleImageView
public class CircleImageView extends ImageView implements View.OnTouchListener {
private static final int[] mStates = { R.attr.state_notset, R.attr.state_on, R.attr.state_off };
private int mStateIndex = 0; // first state is "notset"
private OnStateChangeListener mListener;
private static final ScaleType SCALE_TYPE = ScaleType.CENTER_CROP;
private static final Bitmap.Config BITMAP_CONFIG = Bitmap.Config.ARGB_8888;
private static final int COLORDRAWABLE_DIMENSION = 2;
private static final int DEFAULT_BORDER_WIDTH = 0;
private static final int DEFAULT_BORDER_COLOR = Color.BLACK;
private static final int DEFAULT_FILL_COLOR = Color.TRANSPARENT;
private static final boolean DEFAULT_BORDER_OVERLAY = false;
private final RectF mDrawableRect = new RectF();
private final RectF mBorderRect = new RectF();
private final Matrix mShaderMatrix = new Matrix();
private final Paint mBitmapPaint = new Paint();
private final Paint mBorderPaint = new Paint();
private final Paint mFillPaint = new Paint();
private int mBorderColor = DEFAULT_BORDER_COLOR;
private int mBorderWidth = DEFAULT_BORDER_WIDTH;
private int mFillColor = DEFAULT_FILL_COLOR;
private Bitmap mBitmap;
private BitmapShader mBitmapShader;
private int mBitmapWidth;
private int mBitmapHeight;
private float mDrawableRadius;
private float mBorderRadius;
private ColorFilter mColorFilter;
private boolean mReady;
private boolean mSetupPending;
private boolean mBorderOverlay;
public CircleImageView(Context context) {
super(context);
init();
}
public CircleImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CircleImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleImageView, defStyle, 0);
mBorderWidth = a.getDimensionPixelSize(R.styleable.CircleImageView_civ_border_width, DEFAULT_BORDER_WIDTH);
mBorderColor = a.getColor(R.styleable.CircleImageView_civ_border_color, DEFAULT_BORDER_COLOR);
mBorderOverlay = a.getBoolean(R.styleable.CircleImageView_civ_border_overlay, DEFAULT_BORDER_OVERLAY);
mFillColor = a.getColor(R.styleable.CircleImageView_civ_fill_color, DEFAULT_FILL_COLOR);
a.recycle();
init();
}
private void init() {
super.setScaleType(SCALE_TYPE);
mReady = true;
if (mSetupPending) {
setup();
mSetupPending = false;
}
}
#Override
public ScaleType getScaleType() {
return SCALE_TYPE;
}
#Override
public void setScaleType(ScaleType scaleType) {
if (scaleType != SCALE_TYPE) {
throw new IllegalArgumentException(String.format("ScaleType %s not supported.", scaleType));
}
}
#Override
public void setAdjustViewBounds(boolean adjustViewBounds) {
if (adjustViewBounds) {
throw new IllegalArgumentException("adjustViewBounds not supported.");
}
}
#Override
protected void onDraw(Canvas canvas) {
if (mBitmap == null) {
return;
}
if (mFillColor != Color.TRANSPARENT) {
canvas.drawCircle(getWidth() / 2.0f, getHeight() / 2.0f, mDrawableRadius, mFillPaint);
}
canvas.drawCircle(getWidth() / 2.0f, getHeight() / 2.0f, mDrawableRadius, mBitmapPaint);
if (mBorderWidth != 0) {
canvas.drawCircle(getWidth() / 2.0f, getHeight() / 2.0f, mBorderRadius, mBorderPaint);
}
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
setup();
}
public int getBorderColor() {
return mBorderColor;
}
public void setBorderColor(#ColorInt int borderColor) {
if (borderColor == mBorderColor) {
return;
}
mBorderColor = borderColor;
mBorderPaint.setColor(mBorderColor);
invalidate();
}
public void setBorderColorResource(#ColorRes int borderColorRes) {
setBorderColor(getContext().getResources().getColor(borderColorRes));
}
public int getFillColor() {
return mFillColor;
}
public void setFillColor(#ColorInt int fillColor) {
if (fillColor == mFillColor) {
return;
}
mFillColor = fillColor;
mFillPaint.setColor(fillColor);
invalidate();
}
public void setFillColorResource(#ColorRes int fillColorRes) {
setFillColor(getContext().getResources().getColor(fillColorRes));
}
public int getBorderWidth() {
return mBorderWidth;
}
public void setBorderWidth(int borderWidth) {
if (borderWidth == mBorderWidth) {
return;
}
mBorderWidth = borderWidth;
setup();
}
public boolean isBorderOverlay() {
return mBorderOverlay;
}
public void setBorderOverlay(boolean borderOverlay) {
if (borderOverlay == mBorderOverlay) {
return;
}
mBorderOverlay = borderOverlay;
setup();
}
#Override
public void setImageBitmap(Bitmap bm) {
super.setImageBitmap(bm);
mBitmap = bm;
setup();
}
#Override
public void setImageDrawable(Drawable drawable) {
super.setImageDrawable(drawable);
mBitmap = getBitmapFromDrawable(drawable);
setup();
}
#Override
public void setImageResource(#DrawableRes int resId) {
super.setImageResource(resId);
mBitmap = getBitmapFromDrawable(getDrawable());
setup();
}
#Override
public void setImageURI(Uri uri) {
super.setImageURI(uri);
mBitmap = uri != null ? getBitmapFromDrawable(getDrawable()) : null;
setup();
}
#Override
public void setColorFilter(ColorFilter cf) {
if (cf == mColorFilter) {
return;
}
mColorFilter = cf;
applyColorFilter();
invalidate();
}
#Override
public ColorFilter getColorFilter() {
return mColorFilter;
}
private void applyColorFilter() {
if (mBitmapPaint != null) {
mBitmapPaint.setColorFilter(mColorFilter);
}
}
private Bitmap getBitmapFromDrawable(Drawable drawable) {
if (drawable == null) {
return null;
}
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
try {
Bitmap bitmap;
if (drawable instanceof ColorDrawable) {
bitmap = Bitmap.createBitmap(COLORDRAWABLE_DIMENSION, COLORDRAWABLE_DIMENSION, BITMAP_CONFIG);
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), BITMAP_CONFIG);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private void setup() {
if (!mReady) {
mSetupPending = true;
return;
}
if (getWidth() == 0 && getHeight() == 0) {
return;
}
if (mBitmap == null) {
invalidate();
return;
}
mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mBitmapPaint.setAntiAlias(true);
mBitmapPaint.setShader(mBitmapShader);
mBorderPaint.setStyle(Paint.Style.STROKE);
mBorderPaint.setAntiAlias(true);
mBorderPaint.setColor(mBorderColor);
mBorderPaint.setStrokeWidth(mBorderWidth);
mFillPaint.setStyle(Paint.Style.FILL);
mFillPaint.setAntiAlias(true);
mFillPaint.setColor(mFillColor);
mBitmapHeight = mBitmap.getHeight();
mBitmapWidth = mBitmap.getWidth();
mBorderRect.set(0, 0, getWidth(), getHeight());
mBorderRadius = Math.min((mBorderRect.height() - mBorderWidth) / 2.0f, (mBorderRect.width() - mBorderWidth) / 2.0f);
mDrawableRect.set(mBorderRect);
if (!mBorderOverlay) {
mDrawableRect.inset(mBorderWidth, mBorderWidth);
}
mDrawableRadius = Math.min(mDrawableRect.height() / 2.0f, mDrawableRect.width() / 2.0f);
applyColorFilter();
updateShaderMatrix();
invalidate();
}
private void updateShaderMatrix() {
float scale;
float dx = 0;
float dy = 0;
mShaderMatrix.set(null);
if (mBitmapWidth * mDrawableRect.height() > mDrawableRect.width() * mBitmapHeight) {
scale = mDrawableRect.height() / (float) mBitmapHeight;
dx = (mDrawableRect.width() - mBitmapWidth * scale) * 0.5f;
} else {
scale = mDrawableRect.width() / (float) mBitmapWidth;
dy = (mDrawableRect.height() - mBitmapHeight * scale) * 0.5f;
}
mShaderMatrix.setScale(scale, scale);
mShaderMatrix.postTranslate((int) (dx + 0.5f) + mDrawableRect.left, (int) (dy + 0.5f) + mDrawableRect.top);
mBitmapShader.setLocalMatrix(mShaderMatrix);
}
#Override
public int[] onCreateDrawableState(int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace+1);
int [] state = { mStates[mStateIndex] };
mergeDrawableStates(drawableState, state);
return drawableState;
}
public void setOnStateChangedListener(OnStateChangeListener l) {
this.mListener = l;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.e("STATETOUCH", "onTouch: down");
mStateIndex = 1;
if(mListener != null) mListener.onStateChanged(mStates[1]);
return true;
case MotionEvent.ACTION_UP:
Log.e("STATETOUCH", "onTouch: up");
mStateIndex = 2;
if(mListener != null) mListener.onStateChanged(mStates[2]);
return false;
}
return false;
}
}
EDIT in attrs.xml:
and this in attrs.xml
<declare-styleable name="CircleImageView">
<attr name="civ_border_width" format="dimension" />
<attr name="civ_border_color" format="color" />
<attr name="civ_border_overlay" format="boolean" />
<attr name="civ_fill_color" format="color" />
<attr name="state_on" format="boolean" />
<attr name="state_off" format="boolean" />
</declare-styleable>
and use it like this in your code :
<com.yourpackagename.CircleImageView
android:layout_width="64dp"
android:layout_height="64dp"
android:id="#+id/img"
app:civ_border_width="1dp"
app:civ_border_color="#000"
android:src="#drawable/profile_pic"/>
and then in your code do the following:
yourImageView.setOnStateChangedListener(new OnStateChangeListener() {
#Override
public void onStateChanged(int state) {
switch (state){
case R.attr.state_on:
yourImageView.setBorderColor(Color.parseColor("#00ff00"));
break;
case R.attr.state_off:
yourImageView.setBorderColor(Color.parseColor("#ff00ff"));
//do anything you would do after onclick of this imageview here, like open a new activity.
break;
}
Log.e("STATECHANGE", "State changed to: " + context.getResources().getResourceEntryName(state));
}
});
reference : https://stackoverflow.com/a/21969864/2251837
As you can see this code works fine for me. Can you post your code, how you did it, then may be I will be able to help?
EDIT: This is what you need to change in your getView() method :
view.setOnTouchListener(new View.OnTouchListener() { // here view is this view : View view = inflater.inflate(type == List_Section ? R.layout.section : R.layout.listitem, parent, false);
#Override
public boolean onTouch(View v, MotionEvent event) {
small_profile.dispatchTouchEvent(event);
return false;
}
});
You need to draw 2 bitmap here to activate Xfermode:
private Bitmap maskingImage(Bitmap s1, Bitmap s2) {
Bitmap result = Bitmap.createBitmap(s2.getWidth(), s2.getHeight(), Bitmap.Config.ARGB_8888);
Canvas mCanvas = new Canvas(result);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
mCanvas.drawBitmap(s1, 0, 0, null);
mCanvas.drawBitmap(s2, 0, 0, paint);
paint.setXfermode(null);
return result;
}
s2 is ur circle, s1 is ur image. If you want to change to Mode.SRC_IN, just swap s1 and s2 param position

Undo function on bitmap is not working

I'm working on a drawing app but facing some undo problems. When i paint into the image and then press the undo button it won't undo my last action. I'm stuck on it. I'm using floodfill algorithm.
Here is the image below
Look at the Undo function in the code below, i think i did it right but please check it and tell me where is the actual problem.
public class MainActivity extends AppCompatActivity implements
View.OnTouchListener {
Button red, blue, yellow, undo;
Paint paint;
private RelativeLayout drawingLayout;
private MyView myView;
private ArrayList<Path> paths = new ArrayList<>();
private ArrayList<Path> undonePaths = new ArrayList<Path>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myView = new MyView(this);
drawingLayout = (RelativeLayout) findViewById(R.id.relative_layout);
drawingLayout.addView(myView);
red = (Button) findViewById(R.id.btn_red);
blue = (Button) findViewById(R.id.btn_blue);
yellow = (Button) findViewById(R.id.btn_yellow);
undo = (Button) findViewById(R.id.undo);
red.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
paint.setColor(Color.RED);
}
});
yellow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
paint.setColor(Color.YELLOW);
}
});
blue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
paint.setColor(Color.BLUE);
}
});
undo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myView.onClickUndo();
}
});
}
#Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
public class MyView extends View {
final Point p1 = new Point();
Bitmap mBitmap;
ProgressDialog pd;
Canvas canvas;
private Path path;
public MyView(Context context) {
super(context);
paint = new Paint();
paint.setAntiAlias(true);
pd = new ProgressDialog(context);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(5f);
mBitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.gp1_1).copy(Bitmap.Config.ARGB_8888, true);
this.path = new Path();
}
public void onClickUndo() {
if (paths.size()>0) {
undonePaths.add(paths.remove(paths.size()-1));
invalidate();
} else {
Toast.makeText(getContext(), getString(R.string.nomore), Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onDraw(Canvas canvas) {
this.canvas = canvas;
paint.setColor(Color.GREEN);
canvas.drawBitmap(mBitmap, 0, 0, paint);
for (Path p : paths) {
canvas.drawPath(p, paint);
}
canvas.drawPath(path,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();
paths.add(path);
invalidate();
}
return true;
}
public void clear() {
path.reset();
invalidate();
}
public int getCurrentPaintColor() {
return paint.getColor();
}
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(getString(R.string.wait));
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();
}
}
}
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);
}
}
}
}

Progress bar with divider

Can someone please explain to me how to implement a progress bar with a divider just like its shown on the image below?
For the progress bar I am using https://github.com/akexorcist/Android-RoundCornerProgressBar but this does not seem to have a divider option.
replace ProgressDrawable from my answer with the modified one:
class ProgressDrawable extends Drawable {
private static final int NUM_SEGMENTS = 4;
private final int mForeground;
private final int mBackground;
private final Paint mPaint = new Paint();
private final RectF mSegment = new RectF();
public ProgressDrawable(int fgColor, int bgColor) {
mForeground = fgColor;
mBackground = bgColor;
}
#Override
protected boolean onLevelChange(int level) {
invalidateSelf();
return true;
}
#Override
public void draw(Canvas canvas) {
float level = getLevel() / 10000f;
Rect b = getBounds();
float gapWidth = b.height() / 2f;
float segmentWidth = (b.width() - (NUM_SEGMENTS - 1) * gapWidth) / NUM_SEGMENTS;
mSegment.set(0, 0, segmentWidth, b.height());
mPaint.setColor(mForeground);
for (int i = 0; i < NUM_SEGMENTS; i++) {
float loLevel = i / (float) NUM_SEGMENTS;
float hiLevel = (i + 1) / (float) NUM_SEGMENTS;
if (loLevel <= level && level <= hiLevel) {
float middle = mSegment.left + NUM_SEGMENTS * segmentWidth * (level - loLevel);
canvas.drawRect(mSegment.left, mSegment.top, middle, mSegment.bottom, mPaint);
mPaint.setColor(mBackground);
canvas.drawRect(middle, mSegment.top, mSegment.right, mSegment.bottom, mPaint);
} else {
canvas.drawRect(mSegment, mPaint);
}
mSegment.offset(mSegment.width() + gapWidth, 0);
}
}
#Override
public void setAlpha(int alpha) {
}
#Override
public void setColorFilter(ColorFilter cf) {
}
#Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
}
and create it like this:
Drawable d = new ProgressDrawable(0xdd00ff00, 0x4400ff00);
/**
* Created by nagendra on 16/06/15.
*/
public class ProgressBarDrawable extends Drawable {
private int parts = 10;
private Paint paint = null;
private int fillColor = Color.parseColor("#2D6EB9");
private int emptyColor = Color.parseColor("#233952");
private int separatorColor = Color.parseColor("#FFFFFF");
private RectF rectFill = null;
private RectF rectEmpty = null;
private List<RectF> separators = null;
public ProgressBarDrawable(int parts)
{
this.parts = parts;
this.paint = new Paint(Paint.ANTI_ALIAS_FLAG);
this.separators = new ArrayList<RectF>();
}
#Override
protected boolean onLevelChange(int level)
{
invalidateSelf();
return true;
}
#Override
public void draw(Canvas canvas)
{
// Calculate values
Rect b = getBounds();
float width = b.width();
float height = b.height();
int spaceFilled = (int)(getLevel() * width / 10000);
this.rectFill = new RectF(0, 0, spaceFilled, height);
this.rectEmpty = new RectF(spaceFilled, 0, width, height);
int spaceBetween = (int)(width / 100);
int widthPart = (int)(width / this.parts - (int)(0.9 * spaceBetween));
int startX = widthPart;
for (int i=0; i<this.parts - 1; i++)
{
this.separators.add( new RectF(startX, 0, startX + spaceBetween, height) );
startX += spaceBetween + widthPart;
}
// Foreground
this.paint.setColor(this.fillColor);
canvas.drawRect(this.rectFill, this.paint);
// Background
this.paint.setColor(this.emptyColor);
canvas.drawRect(this.rectEmpty, this.paint);
// Separator
this.paint.setColor(this.separatorColor);
for (RectF separator : this.separators)
{
canvas.drawRect(separator, this.paint);
}
}
#Override
public void setAlpha(int alpha)
{
}
#Override
public void setColorFilter(ColorFilter cf)
{
}
#Override
public int getOpacity()
{
return PixelFormat.TRANSLUCENT;
}
}
in XM Layout
<ProgressBar
android:id="#+id/progress_bar_test"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="?android:attr/progressBarStyleHorizontal"
android:max="100"
android:progress="10"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
/>
ProgressBar progressBar= (ProgressBar)findViewById(R.id.progress_bar_test);
ProgressBarDrawable bgProgress= new ProgressBarDrawable(5);
progressBar.setProgressDrawable(bgProgress);
With the help of this and this answers, I could create my customized version of the segmented horizontal progress bar.
First, Create a class as follows.
public class SegmentedProgressDrawable extends Drawable {
private int parts;
private Paint paint;
private int fillColor;
private int emptyColor;
private int cutOffWidth;
private int separatorColor;
public SegmentedProgressDrawable(int parts, int fillColor, int emptyColor, int separatorColor) {
this.parts = parts;
this.fillColor = fillColor;
this.emptyColor = emptyColor;
this.separatorColor = separatorColor;
this.paint = new Paint(Paint.ANTI_ALIAS_FLAG);
}
#Override
protected boolean onLevelChange(int level) {
invalidateSelf();
return true;
}
#Override
public void draw(#NonNull Canvas canvas) {
// Calculate values
Rect bounds = getBounds();
float actualWidth = bounds.width();
float actualHeight = bounds.height();
//width with dividers + segment width
int fullBlockWidth = (int) (actualWidth / this.parts);
//ToDo: to change the width of segment change this line
int segmentWidth = (int) (fullBlockWidth * 0.2f);
// int dividerWidth =fullBlockWidth-segmentWidth;
cutOffWidth = (int) (getLevel() * actualWidth / 10000);
//Draw separator as background
RectF fullBox = new RectF(0, 0, actualWidth, actualHeight);
this.paint.setColor(this.separatorColor);
canvas.drawRect(fullBox, this.paint);
//start drawing lines as segmented bars
int startX = 0;
for (int i = 0; i < this.parts; i++) {
int endX = startX + segmentWidth;
//in ideal condition this would be the rectangle
RectF part = new RectF(startX, 0, endX, actualHeight);
//if the segment is below level the paint color should be fill color
if ((startX + segmentWidth) <= cutOffWidth) {
this.paint.setColor(this.fillColor);
canvas.drawRect(part, this.paint);
}
//if the segment is started below the level but ends above the level than we need to create 2 different rectangle
else if (startX < cutOffWidth) {
RectF part1 = new RectF(startX, 0, cutOffWidth, actualHeight);
this.paint.setColor(this.fillColor);
canvas.drawRect(part1, this.paint);
RectF part2 = new RectF(cutOffWidth, 0, startX + segmentWidth, actualHeight);
this.paint.setColor(this.emptyColor);
canvas.drawRect(part2, this.paint);
}
//if the segment is above level the paint color should be empty color
else {
this.paint.setColor(this.emptyColor);
canvas.drawRect(part, this.paint);
}
//update the startX to start the new segment with the gap of divider and segment width
startX += fullBlockWidth;
}
}
#Override
public void setAlpha(int alpha) {
}
#Override
public void setColorFilter(ColorFilter cf) {
}
#Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
}
And I, used it as follows:
horizontalProgressBar = findViewById(R.id.horizontal_progress_bar);
int fillColor = ContextCompat.getColor(getActivity(), R.color.primary);
int emptyColor = ContextCompat.getColor(getActivity(), R.color.color_redeem_badge_bg);
int separatorColor = ContextCompat.getColor(getActivity(), R.color.transparent);
SegmentedProgressDrawable progressDrawable = new SegmentedProgressDrawable(20, fillColor, emptyColor, separatorColor);
horizontalProgressBar.setProgressDrawable(progressDrawable);
horizontalProgressBar.setProgress(60);

OnClick on custom view is not working

I have a LinearLayout where I need to add custom view dynamically. custom view is added properly. but now i want to set on click on that view. I have tired it.
BlockView localView = new BlockView(getApplicationContext(),
BitmapFactory.decodeFile(imagePath);
localView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
layoutBox.addView(localView);
BlockView.java
public class BlockView extends View{
Bitmap mBitmap;
Drawable mDrawable;
private int drawableWidth, drawableHeight;
private int viewWidth, viewHeight, layoutHeight, layoutWidth;
private Matrix matrix = new Matrix();
private Paint mBorderPaint;
public BlockView(Context c) {
super(c);
setFocusable(true);
}
public BlockView(Context c, AttributeSet attrs) {
super(c, attrs);
setDrawingCacheEnabled(true);
}
public BlockView(Context paramContext, Bitmap bmp, int layoutHeight,
int layoutWidth) {
super(paramContext);
this.mBitmap = bmp;
this.layoutHeight = layoutHeight;
this.layoutWidth = layoutWidth;
mBorderPaint = new Paint();
// mBorderPaint.setAntiAlias(true);
mBorderPaint.setStyle(Paint.Style.STROKE);
mBorderPaint.setColor(Color.GREEN);
mBorderPaint.setStrokeWidth(10);
setDrawingCacheEnabled(true);
buildDrawingCache(true);
mDrawable = new BitmapDrawable(getResources(), mBitmap);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
drawableWidth = mDrawable.getIntrinsicWidth();
drawableHeight = mDrawable.getIntrinsicHeight();
viewWidth = layoutWidth;
viewHeight = layoutHeight;
setMeasuredDimension(viewWidth, viewHeight);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
try {
int saveCount = canvas.save();
float scale;
float dx;
float dy;
if (drawableWidth <= viewWidth && drawableHeight <= viewHeight) {
scale = 1.0f;
} else {
scale = Math.min((float) viewWidth / (float) drawableWidth,
(float) viewHeight / (float) drawableHeight);
}
dx = (int) ((viewWidth - drawableWidth * scale) * 0.5f + 0.5f);
dy = (int) ((viewHeight - drawableHeight * scale) * 0.5f + 0.5f);
matrix.setScale(scale, scale);
matrix.postTranslate(dx, dy);
canvas.concat(matrix);
mDrawable.setBounds(0, 0, drawableWidth, drawableHeight);
mDrawable.draw(canvas);
canvas.restoreToCount(saveCount);
} catch (Exception ex) {
Log.e("onDraw: ", ex.getMessage());
ex.printStackTrace();
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
return true;
}
}
But onClick is not working.I don't know where i am going wrong.
Help me to fix it !!
First you need to addView() on layout and after that need to register clickLisner.
layoutBox.addView(localView); // this line will become first.
localView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
Is the onclickListener generated automatically, I mean you should use View.OnClickListener. If that is not used you can't override the onClickListener
localView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
layoutBox.addView(localView);
Try out this hope it will help you
// viewHolder is your View Custom view
#Override
public void setOnClickListener(OnClickListener l) {
if (l == null) {
viewHolder.setOnClickListener(null);
mParentOnClickListener = null;
} else {
viewHolder.setOnClickListener(mOnClickListener);
mParentOnClickListener = l;
}
}
private View.OnClickListener mParentOnClickListener;
private View.OnClickListener mOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if (mParentOnClickListener != null) {
mParentOnClickListener.onClick(YourCustomView.this);
}
}
};

How to draw lines in different colors?

I have developed an application which draws lines on the screen .I want to use different colors for the lines but all the lines are appearing in same color.
I have a color picker in my code to change the colors and i want to draw lines of different colors each time by selecting colors, but as of now since i am constructing lines and rendering it.When i choose initially red and draw a line, and then later select blue and draw a line , now the older line is also getting changed to blue instead of red, However i want the red to remain as red, and blue as such can any one help?
My code is given below
MyDemo.java:
public class MyDemo extends Activity implements
ColorPickerDialog.OnColorChangedListener {
private LinearLayout root;
private Button btnReset;
private Button btnPickColor;
public static int selectedColor = Color.BLACK;
MyImageView view;
private static final String COLOR_PREFERENCE_KEY = "color";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_demo);
root = (LinearLayout) findViewById(R.id.root);
btnReset = (Button) findViewById(R.id.reset);
btnPickColor = (Button) findViewById(R.id.pickColor);
final MyImageView view = new MyImageView(this);
view.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.FILL_PARENT));
root.addView(view);
btnReset.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
view.reset();
}
});
btnPickColor.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// color picker class call
int color = PreferenceManager.getDefaultSharedPreferences(
MyDemo.this).getInt(COLOR_PREFERENCE_KEY, Color.WHITE);
new ColorPickerDialog(MyDemo.this, MyDemo.this, color).show();
}
});
}
public void colorChanged(int color) {
PreferenceManager.getDefaultSharedPreferences(this).edit()
.putInt(COLOR_PREFERENCE_KEY, color).commit();
selectedColor = color;
}
}
MyImageView.java:
public class MyImageView extends ImageView implements View.OnTouchListener {
private int id = -1;
private Path path;
private List<Path> paths = new ArrayList<Path>();
private List<PointF> points = new ArrayList<PointF>();
boolean multiTouch = false;
MyDemo demo;
public MyImageView(Context context) {
super(context);
this.setOnTouchListener(this);
Log.d("Constructor", " Control in constructor");
}
public void reset() {
paths.clear();
points.clear();
path = null;
id = -1;
invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int colorPicked = MyDemo.selectedColor;
if (colorPicked != Color.BLACK) {
Paint paint = createPen(colorPicked);
paint.setStyle(Paint.Style.STROKE);
for (Path path : paths) {
canvas.drawPath(path, paint);
}
for (int i = 0; i < points.size(); i++) {
PointF p = points.get(i);
canvas.drawText("" + p.x, p.y, i, createPen(colorPicked));
}
} else {
Paint paint = createPen(colorPicked);
paint.setStyle(Paint.Style.STROKE);
for (Path path : paths) {
canvas.drawPath(path, paint);
}}
for (int i = 0; i < points.size(); i++) {
PointF p = points.get(i);
canvas.drawText("" + p.x, p.y, i, createPen(colorPicked));
}
}
private PointF copy(PointF p) {
PointF copy = new PointF();
copy.set(p);
return copy;
}
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
multiTouch = false;
id = event.getPointerId(0);
PointF p = getPoint(event, id);
path = new Path();
path.moveTo(p.x, p.y);
paths.add(path);
points.add(copy(p));
break;
case MotionEvent.ACTION_POINTER_DOWN:
multiTouch = true;
for (int i = 0; i < event.getPointerCount(); i++) {
int tId = event.getPointerId(i);
if (tId != id) {
points.add(getPoint(event, i));
}
}
break;
case MotionEvent.ACTION_MOVE:
if (!multiTouch) {
p = getPoint(event, id);
path.lineTo(p.x, p.y);
}
break;
}
invalidate();
return true;
}
private PointF getPoint(MotionEvent event, int i) {
int index = 0;
return new PointF(event.getX(index), event.getY(index));
}
public Paint createPen(int color) {
Paint pen = new Paint();
pen.setColor(color);
float width = 3;
pen.setStrokeWidth(width);
return pen;
}
}
ColorPickerDialog.java:
public class ColorPickerDialog extends Dialog {
public interface OnColorChangedListener {
void colorChanged(int color);
}
private final OnColorChangedListener mListener;
private final int mInitialColor;
private static class ColorPickerView extends View {
private final Paint mPaint;
private final Paint mCenterPaint;
private final int[] mColors;
private final OnColorChangedListener mListener;
ColorPickerView(Context c, OnColorChangedListener l, int color) {
super(c);
mListener = l;
mColors = new int[] { 0xFFFF0000, 0xFFFF00FF, 0xFF0000FF,
0xFF00FFFF, 0xFF00FF00, 0xFFFFFF00, 0xFFFF0000 };
Shader s = new SweepGradient(0, 0, mColors, null);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setShader(s);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(32);
mCenterPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mCenterPaint.setColor(color);
mCenterPaint.setStrokeWidth(5);
}
private boolean mTrackingCenter;
private boolean mHighlightCenter;
#Override
protected void onDraw(Canvas canvas) {
float r = CENTER_X - mPaint.getStrokeWidth() * 0.5f;
canvas.translate(CENTER_X, CENTER_X);
canvas.drawOval(new RectF(-r, -r, r, r), mPaint);
canvas.drawCircle(0, 0, CENTER_RADIUS, mCenterPaint);
if (mTrackingCenter) {
int c = mCenterPaint.getColor();
mCenterPaint.setStyle(Paint.Style.STROKE);
if (mHighlightCenter) {
mCenterPaint.setAlpha(0xFF);
} else {
mCenterPaint.setAlpha(0x80);
}
canvas.drawCircle(0, 0, CENTER_RADIUS
+ mCenterPaint.getStrokeWidth(), mCenterPaint);
mCenterPaint.setStyle(Paint.Style.FILL);
mCenterPaint.setColor(c);
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(CENTER_X * 2, CENTER_Y * 2);
}
private static final int CENTER_X = 100;
private static final int CENTER_Y = 100;
private static final int CENTER_RADIUS = 32;
private int ave(int s, int d, float p) {
return s + java.lang.Math.round(p * (d - s));
}
private int interpColor(int colors[], float unit) {
if (unit <= 0)
return colors[0];
if (unit >= 1)
return colors[colors.length - 1];
float p = unit * (colors.length - 1);
int i = (int) p;
p -= i;
// now p is just the fractional part [0...1) and i is the index
int c0 = colors[i];
int c1 = colors[i + 1];
int a = ave(Color.alpha(c0), Color.alpha(c1), p);
int r = ave(Color.red(c0), Color.red(c1), p);
int g = ave(Color.green(c0), Color.green(c1), p);
int b = ave(Color.blue(c0), Color.blue(c1), p);
return Color.argb(a, r, g, b);
}
private static final float PI = 3.1415926f;
#Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX() - CENTER_X;
float y = event.getY() - CENTER_Y;
boolean inCenter = java.lang.Math.sqrt(x * x + y * y) <= CENTER_RADIUS;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mTrackingCenter = inCenter;
if (inCenter) {
mHighlightCenter = true;
invalidate();
break;
}
case MotionEvent.ACTION_MOVE:
if (mTrackingCenter) {
if (mHighlightCenter != inCenter) {
mHighlightCenter = inCenter;
invalidate();
}
} else {
float angle = (float) java.lang.Math.atan2(y, x);
// need to turn angle [-PI ... PI] into unit [0....1]
float unit = angle / (2 * PI);
if (unit < 0) {
unit += 1;
}
mCenterPaint.setColor(interpColor(mColors, unit));
invalidate();
}
break;
case MotionEvent.ACTION_UP:
if (mTrackingCenter) {
if (inCenter) {
mListener.colorChanged(mCenterPaint.getColor());
}
mTrackingCenter = false; // so we draw w/o halo
invalidate();
}
break;
}
return true;
}
}
public ColorPickerDialog(Context context, OnColorChangedListener listener,
int initialColor) {
super(context);
mListener = listener;
mInitialColor = initialColor;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
OnColorChangedListener l = new OnColorChangedListener() {
public void colorChanged(int color) {
mListener.colorChanged(color);
dismiss();
}
};
LinearLayout layout = new LinearLayout(getContext());
layout.setOrientation(LinearLayout.VERTICAL);
layout.setGravity(Gravity.CENTER);
layout.setPadding(10, 10, 10, 10);
layout.addView(new ColorPickerView(getContext(), l, mInitialColor),
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
setContentView(layout);
setTitle("Pick a Color");
}
}
I'm not sure but it seams a problem is in your onDraw method
Paint paint = createPen(colorPicked);
paint.setStyle(Paint.Style.STROKE);
for (Path path : paths) {
canvas.drawPath(path, paint);
}
You select a color first (it's the last color you picked) and then with a same color you draw each path.
I think that the solution for this could be to create array of colors which will contain color for every path you create and to pick corresponding color before you draw each path
try this, it will help you
#Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
int colorPicked = MainActivity.selectedColor;
paint1 = createPen(colorPicked);
for (Path p : paths){
canvas.drawPath(p, paint1);
paint1.setColor(colorPicked);
}
}
private Paint createPen(int color) {
// TODO Auto-generated method stub
paint1 = new Paint();
paint1.setAntiAlias(true);
paint1.setDither(true);
paint1.setStyle(Paint.Style.STROKE);
paint1.setStrokeJoin(Paint.Join.ROUND);
paint1.setStrokeCap(Paint.Cap.ROUND);
paint1.setStrokeWidth(3);
return paint1;
}

Categories

Resources