I try to create like this drawable
I wrote code and almost working correctly
public class GetsugaDrawable extends Drawable {
private final Context context;
private final float radiusScale = 1.2f;
private final float yOffset = 0.3f;
private final int colorLower = Color.RED;
private final int colorUpper = Color.BLACK;
private final Paint upperPaint = new Paint();
public GetsugaDrawable(Context c) {
context = c;
upperPaint.setColor(colorUpper);
upperPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
}
#Override
public void draw(#NonNull Canvas canvas) {
final Rect bounds = new Rect(getBounds());
canvas.drawColor(colorLower, PorterDuff.Mode.SRC);
final float radius = radiusScale * bounds.height();
final int x = bounds.centerX();
final float y = (bounds.centerY() - bounds.height() * yOffset) - radius;
canvas.drawCircle(x, y, radius, upperPaint);
}
#Override
public void setAlpha(int alpha) {
// ignored TODO impl.
}
#Override
public void setColorFilter(#Nullable ColorFilter colorFilter) {
// ignored TODO impl.
}
#Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
}
Here is my result
I tried to change
private final int colorUpper = Color.BLACK;
with
private final int colorUpper = Color.TRANSPARENT;
but when I run my app again with transparent color, the result is like this
What am i doing wrong ?
Thanks
Add upperPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
public class GetsugaDrawable extends Drawable {
private final Context context;
private final float radiusScale = 1.2f;
private final float yOffset = 0.3f;
private final int colorLower = Color.RED;
private final int colorUpper = Color.BLACK;
private final Paint upperPaint = new Paint();
public GetsugaDrawable(Context c) {
context = c;
upperPaint.setAntiAlias(true);
upperPaint.setColor(colorUpper);
upperPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
}
#Override
public void draw(#NonNull Canvas canvas) {
final Rect bounds = new Rect(getBounds());
canvas.drawColor(colorLower);
final float radius = radiusScale * bounds.height();
final int x = bounds.centerX();
final float y = (bounds.centerY() - bounds.height() * yOffset) - radius;
canvas.drawCircle(x, y, radius, upperPaint);
}
#Override
public void setAlpha(int alpha) {
}
#Override
public void setColorFilter(#Nullable ColorFilter colorFilter) {
}
#Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}}
And don't forget to view.setLayerType(View.LAYER_TYPE_HARDWARE, null); on target view
You can change draw function.
#Override
public void draw(#NonNull Canvas canvas) {
final Rect bounds = new Rect(getBounds());
final float radius = radiusScale * bounds.height();
final int x = bounds.centerX();
final float y = (bounds.centerY() - bounds.height() * yOffset) - radius;
Path path = new Path();
path.addCircle(x, y, radius, CW);
canvas.clipPath(path, Region.Op.DIFFERENCE);
canvas.drawColor(colorLower);
}
Try this.
Related
how is possible to set an image or icon in the canvas Circle? i have a custom canvas view that by move the camera on map, resize method will be activate and change the shape of the view and by stop the moving of map it will be like factory setting...happy english :-))))
public class CancvasCircle extends androidx.appcompat.widget.AppCompatImageView {
///main circle resize fields
public static final int MAIN_CIRCLE_PRE_RADIUS = 40;
public static final int MAIN_CIRCLE_POST_RADIUS = 43;
public static final String MAIN_CIRCLE_PRE_STROKE_COLOR = "#69DAE2";
//4CEAE3
public static final String MAIN_CIRCLE_POST_STROKE_COLOR = "#FBCC38";
///// line resize fields
public static final int LINE_HIEGHT_STOP = 45;
public static final int LINE_HIEGHT_START_PRE = 0;
public static final int LINE_HIEGHT_START_POST = 23;
public static final int SHADOW_CIRCLE_PRE_RADIUS = 15;
//circle paint fields
Paint strokeCircle;
Paint fillCircle;
Paint shadowCircle;
Paint line;
Paint dot;
//center
float centerX;
float centerY;
//main circle fields
private int radiusMain = MAIN_CIRCLE_PRE_RADIUS;
private String colorMain = MAIN_CIRCLE_PRE_STROKE_COLOR;
//line fields
private float lineStartY;
private float lineStopY;
//shadow circle fields
private int shadowRadius = SHADOW_CIRCLE_PRE_RADIUS;
public CancvasCircle(Context context) {
super(context);
init();
}
public CancvasCircle(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public CancvasCircle(Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public void init() {
strokeCircle = new Paint();
strokeCircle.setAntiAlias(true);
strokeCircle.setAntiAlias(true);
strokeCircle.setStrokeWidth(10);
strokeCircle.setStyle(Paint.Style.STROKE);
fillCircle = new Paint();
fillCircle.setAntiAlias(true);
fillCircle.setColor(Color.parseColor("#BEC6CC"));
fillCircle.setStyle(Paint.Style.FILL);
shadowCircle = new Paint();
shadowCircle.setAntiAlias(true);
shadowCircle.setColor(Color.parseColor("#1f000000"));
shadowCircle.setStyle(Paint.Style.FILL);
line = new Paint();
line.setAntiAlias(true);
line.setColor(Color.parseColor("#000000"));
line.setStrokeWidth(4);
line.setStyle(Paint.Style.FILL);
dot = new Paint();
dot.setAntiAlias(true);
dot.setColor(Color.parseColor("#000000"));
dot.setStrokeWidth(4);
dot.setStyle(Paint.Style.FILL);
}
public void resizeStrokeCircleParams(Boolean resize) {
if (resize) {
this.radiusMain = MAIN_CIRCLE_POST_RADIUS;
this.colorMain = MAIN_CIRCLE_POST_STROKE_COLOR;
this.lineStartY = centerY - LINE_HIEGHT_START_POST;
this.lineStopY = LINE_HIEGHT_STOP + LINE_HIEGHT_START_POST - 10;
this.shadowRadius = LINE_HIEGHT_START_POST;
} else {
this.radiusMain = MAIN_CIRCLE_PRE_RADIUS;
this.colorMain = MAIN_CIRCLE_PRE_STROKE_COLOR;
this.lineStartY = centerY - LINE_HIEGHT_START_PRE;
this.lineStopY = LINE_HIEGHT_STOP;
this.shadowRadius = SHADOW_CIRCLE_PRE_RADIUS;
}
invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
centerX = getWidth() / 2f;
centerY = getHeight() / 2f;
int radius = radiusMain;
float lineStopY = this.lineStopY;
float lineStartY = this.lineStartY;
int shadowRadius = this.shadowRadius;
strokeCircle.setColor(Color.parseColor(colorMain));
canvas.drawCircle(centerX, centerY - lineStopY - radius, radius, strokeCircle);
canvas.drawCircle(centerX, centerY - lineStopY - radius, radius, fillCircle);
canvas.drawCircle(centerX, centerY, shadowRadius, shadowCircle);
canvas.drawLine(centerX, lineStartY, centerX, centerY - lineStopY, line);
canvas.drawPoint(centerX,centerY,dot);
}
}
is it possible to flip two images like coin in it????
See example as custom View.
public class ViewCircle extends View{
final Bitmap bms; //source
final Bitmap bmm; //mask
final Paint paint;
public ViewCircle( Context context ){
super( context );
bms = BitmapFactory.decodeResource( getResources(), R.drawable.pr_0000 );
bmm = Bitmap.createBitmap( bms.getWidth(), bms.getHeight(), Bitmap.Config.ARGB_8888 );
Canvas canvas = new Canvas( bmm );
paint = new Paint( Paint.ANTI_ALIAS_FLAG );
canvas.drawCircle( bmm.getWidth()/2, bmm.getHeight()/2, Math.min(bmm.getWidth()/2,bmm.getHeight()/2), paint );
paint.setXfermode( new PorterDuffXfermode( PorterDuff.Mode.SRC_IN ) );
canvas.drawBitmap( bms, 0, 0, paint );
}
#Override
protected void onDraw( Canvas canvas ){
super.onDraw( canvas );
canvas.drawBitmap( bms, 0,0, null );
canvas.drawBitmap( bmm, bms.getWidth(),0, null );
}
}
i used this method to create a bitmap from XML layout and set it in my codes...
public Bitmap getMarkerBitmapFromView(#DrawableRes int resIdMain, #DrawableRes int resId) {
View customMarkerView = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_marker, null);
customMarkerView.findViewById(R.id.custom_marker_firstlayout);
if(resIdMain != 0){
customMarkerView.setBackgroundResource(resIdMain);
}
ImageView markerImageView = (ImageView) customMarkerView.findViewById(R.id.custom_marker_secondLayout);
if(resId != 0){
markerImageView.setImageResource(resId);
}
customMarkerView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
customMarkerView.layout(0, 0, customMarkerView.getMeasuredWidth(), customMarkerView.getMeasuredHeight());
customMarkerView.buildDrawingCache();
Bitmap returnedBitmap = Bitmap.createBitmap(customMarkerView.getMeasuredWidth(), customMarkerView.getMeasuredHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
canvas.drawColor(Color.WHITE, PorterDuff.Mode.SRC_IN);
Drawable drawable = customMarkerView.getBackground();
if (drawable != null)
drawable.draw(canvas);
customMarkerView.draw(canvas);
return returnedBitmap;
}
and set it in my canvas view in onDraw() and set it in the middle of my circle:
canvas.drawBitmap(getMarkerBitmapFromView(0,guildMarkerICON),convertDpToPixel(76,context),imageHieght,null);
because of drawing wrong in different devices i used this methods to change pixel and dp:
public static float convertPixelsToDp(float px,Context context){
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
float dp = px / (metrics.densityDpi / 160f);
return dp;
}
public static float convertDpToPixel(float dp,Context context){
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
float px = dp * (metrics.densityDpi/160f);
return px;
}
and XML layout that provide my bit map (that you can use image or any things you want in it) is (custom_marker.xml) :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/custom_marker_firstlayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/center_marker_background">
<ImageView
android:id="#+id/custom_marker_secondLayout"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_gravity="center"
android:contentDescription="#null"
/>
</FrameLayout>
and use this method when you want to change the marker(like moving the map):
map.setOnCameraMoveStartedListener(new GoogleMap.OnCameraMoveStartedListener() {
#Override
public void onCameraMoveStarted(int i) {
canvasView.resizeStrokeCircleParams(true,guildMarkerICON);
}
});
map.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
#Override
public void onCameraIdle() {
canvasView.resizeStrokeCircleParams(false,guildMarkerICON);
}
});
and finally here i s my custom canvas class that i used and i passed my custom icon to it by resize method and set it as i want...enjoy it:
public class CancvasCircle extends androidx.appcompat.widget.AppCompatImageView {
///main circle resize fields
public static final int MAIN_CIRCLE_PRE_RADIUS = 24;
public static final int MAIN_CIRCLE_POST_RADIUS = 26;
public static final String MAIN_CIRCLE_PRE_STROKE_COLOR = "#F44336";
public static final String MAIN_CIRCLE_POST_STROKE_COLOR = "#FFCC59";
//FFCC59
//FBCC38
///// line resize fields
public static final int LINE_HIEGHT_STOP = 24;
public static final int LINE_HIEGHT_START_PRE = 0;
public static final int LINE_HIEGHT_START_POST = 11;
public static final int SHADOW_CIRCLE_PRE_RADIUS = 14;
private final Context context;
/// image view fields
//circle paint fields
Paint strokeCircle;
Paint fillCircle;
Paint shadowCircle;
Paint line;
Paint dot;
Paint imagePaint;
//center
float centerX;
float centerY;
//main circle fields
private int radiusMain = MAIN_CIRCLE_PRE_RADIUS;
private String colorMain = MAIN_CIRCLE_PRE_STROKE_COLOR;
//line fieldsاذغ
private float lineStartY;
private float lineStopY;
//shadow circle fields
private int shadowRadius = SHADOW_CIRCLE_PRE_RADIUS;
private Bitmap canvasBitmap;
private int imageTopPadding;
private int guildMarkerICON
;
public CancvasCircle(Context context) {
super(context);
this.context = context;
init();
}
public CancvasCircle(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
this.context = context;
init();
}
public CancvasCircle(Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.context = context;
init();
}
public void init() {
strokeCircle = new Paint();
strokeCircle.setAntiAlias(true);
strokeCircle.setAntiAlias(true);
strokeCircle.setStrokeWidth(12);
strokeCircle.setStyle(Paint.Style.STROKE);
fillCircle = new Paint();
fillCircle.setAntiAlias(true);
fillCircle.setColor(Color.parseColor("#af283232"));
fillCircle.setStyle(Paint.Style.FILL);
shadowCircle = new Paint();
shadowCircle.setAntiAlias(true);
shadowCircle.setColor(Color.parseColor("#1f000000"));
shadowCircle.setStyle(Paint.Style.FILL);
line = new Paint();
line.setAntiAlias(true);
line.setColor(Color.parseColor("#000000"));
line.setStrokeWidth(4);
line.setStyle(Paint.Style.FILL);
dot = new Paint();
dot.setAntiAlias(true);
dot.setColor(Color.parseColor("#000000"));
dot.setStrokeWidth(4);
dot.setStyle(Paint.Style.FILL);
}
public void resizeStrokeCircleParams(Boolean resize , int guildMarkerICON) {
this.guildMarkerICON = guildMarkerICON;
if (resize) {
this.radiusMain = (int) convertDpToPixel(MAIN_CIRCLE_POST_RADIUS,context);
this.colorMain = MAIN_CIRCLE_POST_STROKE_COLOR;
this.lineStartY = centerY -convertDpToPixel( LINE_HIEGHT_START_POST,context);
this.lineStopY =convertDpToPixel( LINE_HIEGHT_STOP,context) + convertDpToPixel(LINE_HIEGHT_START_POST,context) -8;
this.shadowRadius = (int) convertDpToPixel(LINE_HIEGHT_START_POST,context);
this.imageTopPadding = (int) convertDpToPixel(19,context);
} else {
this.radiusMain = (int) convertDpToPixel( MAIN_CIRCLE_PRE_RADIUS,context);
this.colorMain = MAIN_CIRCLE_PRE_STROKE_COLOR;
this.lineStartY = centerY - convertDpToPixel(LINE_HIEGHT_START_PRE,context);
this.lineStopY = convertDpToPixel(LINE_HIEGHT_STOP,context);
this.shadowRadius = (int) convertDpToPixel(SHADOW_CIRCLE_PRE_RADIUS,context);
this.imageTopPadding = (int) convertDpToPixel( 28,context);
}
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
centerX = getWidth() / 2f;
centerY = getHeight() / 2f;
int radius = radiusMain;
float lineStopY = this.lineStopY;
float lineStartY = this.lineStartY;
int shadowRadius = this.shadowRadius;
int imageHieght = this.imageTopPadding;
strokeCircle.setColor(Color.parseColor(colorMain));
// if map is moving (imageHieght == 41)
// if map is not moving (imageHieght == 56)
canvas.drawLine(centerX, lineStartY, centerX, centerY - lineStopY, line);
canvas.drawCircle(centerX, centerY - lineStopY - radius, radius, strokeCircle);
canvas.drawCircle(centerX, centerY - lineStopY - radius, radius, fillCircle);
canvas.drawCircle(centerX, centerY, shadowRadius, shadowCircle);
canvas.drawPoint(centerX,centerY,dot);
canvas.drawBitmap(getMarkerBitmapFromView(0,guildMarkerICON),convertDpToPixel(76,context),imageHieght,null);
invalidate();
}
public static float convertPixelsToDp(float px,Context context){
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
float dp = px / (metrics.densityDpi / 160f);
return dp;
}
public static float convertDpToPixel(float dp,Context context){
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
float px = dp * (metrics.densityDpi/160f);
return px;
}
public Bitmap getMarkerBitmapFromView(#DrawableRes int resIdMain, #DrawableRes int resId) {
View customMarkerView = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_marker, null);
customMarkerView.findViewById(R.id.custom_marker_firstlayout);
if(resIdMain != 0){
customMarkerView.setBackgroundResource(resIdMain);
}
ImageView markerImageView = (ImageView) customMarkerView.findViewById(R.id.custom_marker_secondLayout);
if(resId != 0){
markerImageView.setImageResource(resId);
}
customMarkerView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
customMarkerView.layout(0, 0, customMarkerView.getMeasuredWidth(), customMarkerView.getMeasuredHeight());
customMarkerView.buildDrawingCache();
Bitmap returnedBitmap = Bitmap.createBitmap(customMarkerView.getMeasuredWidth(), customMarkerView.getMeasuredHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
canvas.drawColor(Color.WHITE, PorterDuff.Mode.SRC_IN);
Drawable drawable = customMarkerView.getBackground();
if (drawable != null)
drawable.draw(canvas);
customMarkerView.draw(canvas);
return returnedBitmap;
}
}
result:
I wanted to show profile status using a Progress bar just like Linkedin, I searched everywhere but didn't get any reference related to that.
My code:
public class ProgressDrawable extends Drawable {
private static final int NUM_SEGMENTS = 5;
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() / 10f;
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;
}
}
In this code, all the blocks have same color, but as per requirement, all block colors should be different.
In one of my apps I have created a circular view with multiple colors,In which I want to set click listener on each color arch
Below is the image and code for drawing that view
Custom view class code
public class CircularStatusView extends View {
private static final float DEFAULT_PORTION_WIDTH = 10;
private static final int DEFAULT_PORTION_SPACING = 5;
private static final int DEFAULT_COLOR = Color.parseColor("#D81B60");
private static final float DEFAULT_PORTIONS_COUNT = 1;
private static final float START_DEGREE =-90;
private float radius;
private float portionWidth = DEFAULT_PORTION_WIDTH;
private int portionSpacing = DEFAULT_PORTION_SPACING;
private int portionColor = DEFAULT_COLOR;
private float portionsCount = DEFAULT_PORTIONS_COUNT;
private RectF mBorderRect = new RectF();
private Paint paint;
private SparseIntArray portionToUpdateMap = new SparseIntArray();
private Context context;
public CircularStatusView(Context context) {
super(context);
init(context, null, -1);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircularStatusView, defStyle, 0);
if (a != null) {
portionColor = a.getColor(R.styleable.CircularStatusView_portion_color, DEFAULT_COLOR);
portionWidth = a.getDimensionPixelSize(R.styleable.CircularStatusView_portion_width, (int) DEFAULT_PORTION_WIDTH);
portionSpacing = a.getDimensionPixelSize(R.styleable.CircularStatusView_portion_spacing, DEFAULT_PORTION_SPACING);
portionsCount = a.getInteger(R.styleable.CircularStatusView_portions_count, (int) DEFAULT_PORTIONS_COUNT);
a.recycle();
}
paint = getPaint();
}
public CircularStatusView(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
init(context, attrs, -1);
}
public CircularStatusView(Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mBorderRect.set(calculateBounds());
radius = Math.min((mBorderRect.height() - portionWidth) / 2.0f, (mBorderRect.width() - portionWidth) / 2.0f);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float radius = this.radius;
float center_x = mBorderRect.centerX();
float center_y = mBorderRect.centerY();
final RectF oval = getOval(radius, center_x, center_y);
float degree = 360 / portionsCount;
float percent = 100 / portionsCount;
for (int i = 0; i < portionsCount; i++) {
paint.setColor(getPaintColorForIndex(i));
float startAngle = START_DEGREE + (degree * i);
canvas.drawArc(oval, (getSpacing() / 2) + startAngle, getProgressAngle(percent) - getSpacing(), false, paint);
}
}
private int getPaintColorForIndex(int i) {
if (portionToUpdateMap.indexOfKey(i) >= 0) { //if key is exists
return portionToUpdateMap.get(i);
} else {
return portionColor;
}
}
#NonNull
private RectF getOval(float radius, float center_x, float center_y) {
final RectF oval = new RectF();
oval.set(center_x - radius,
center_y - radius,
center_x + radius,
center_y + radius);
return oval;
}
#NonNull
private Paint getPaint() {
Paint paint = new Paint();
paint.setColor(portionColor);
paint.setStyle(Paint.Style.STROKE);
paint.setAntiAlias(true);
paint.setStrokeWidth(portionWidth);
paint.setStrokeCap(Paint.Cap.BUTT);
return paint;
}
private int getSpacing() {
return portionsCount == 1 ? 0 : portionSpacing;
}
private RectF calculateBounds() {
int availableWidth = getWidth() - getPaddingLeft() - getPaddingRight();
int availableHeight = getHeight() - getPaddingTop() - getPaddingBottom();
int sideLength = Math.min(availableWidth, availableHeight);
float left = getPaddingLeft() + (availableWidth - sideLength) / 2f;
float top = getPaddingTop() + (availableHeight - sideLength) / 2f;
return new RectF(left, top, left + sideLength, top + sideLength);
}
private float getProgressAngle(float percent) {
return percent / (float) 100 * 360;
}
public void setPortionsCount(int portionsCount) {
this.portionsCount = (float) portionsCount;
}
public void setPortionSpacing(int spacing) {
portionSpacing = spacing;
}
public void setPortionWidth(float portionWidth) {
this.portionWidth = portionWidth;
}
public void setCustomPaint(Paint paint) {
this.paint = paint;
}
public void setPortionsColor(int color) {
this.portionColor = color;
portionToUpdateMap.clear();
invalidate();
}
public void setPortionColorForIndex(int index, int color) {
if (index > portionsCount - 1) {
throw new IllegalArgumentException("Index is Bigger than the count!");
} else {
Log.d("3llomi", "adding index to map " + index);
portionToUpdateMap.put(index, color);
invalidate();
}
}
}
and in my activity class
CircularStatusView circularStatusView = findViewById(R.id.circular_status_view);
circularStatusView.setPortionsCount(6);
for (int i=0; i<AppConstants.outerCircleColors.length; i++){
circularStatusView.setPortionColorForIndex(i,Color.parseColor(AppConstants.outerCircleColors[i]));
How I can set click listener on each color arch in this view? Can someone help me out in this?
You can get the pixel from the CircularStatusView, By using OnTouchListener:
CircularStatusView view = ((CircularStatusView)v);
Bitmap bitmap = ((BitmapDrawable)view.getDrawable()).getBitmap();
int pixel = bitmap.getPixel(x,y);
You can just compare the pixel to a different color. Like...
if(pixel == Color.RED){
//It's Red Color
}
You can create an interface listener for onTouch events. Check the onTouch co-ordinates. Depending on their position you can send back the touched part index to the interface listener.
Dummy code:
public class CircularStatusView extends View {
private StatusViewTouchListener listener;
...
..
.
public void setOnClickListener(StatusViewTouchListener listener) {
this.listener = listener;
}
public interface StatusViewTouchListener {
public void onStatusViewTouch(int index);
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
int indexOfTouchedColor;
// Check the touch points and determine in which color part it exists.
listener.onStatusViewTouch(indexOfTouchedColor);
return true;
}
}
Implement the listener where where you are using the view and set it to the View.
public class yourActivity extends Activity implements StatusViewTouchListener {
...
..
.
CircularStatusView circularStatusView = findViewById(R.id.circular_status_view);
circularStatusView.setPortionsCount(6);
for (int i=0; i<AppConstants.outerCircleColors.length; i++){
circularStatusView.setPortionColorForIndex(i,Color.parseColor(AppConstants.outerCircleColors[i]));
circularStatusView.setOnClickListener(this);
...
..
#Override
public void onStatusViewTouch(int index) {
// Perform your action based on the index of the color
}
}
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);
I have a custom view in which i am drawing one big circle and a small circle on the edge of this big circle.
I would like to move the small circle and so would like to have a ontouch listener only for the small circle.
Could some please tell me how to set the ontouch listener for only the small circle.
public class ThermoView extends View{
private ImageView mThermostatBgrd;
private ImageView mCurTempArrow;
private ImageView mSetPointIndicator;
public static final int THEMROSTAT_BACKGROUND = 0;
public static final int THEMROSTAT_CURR_TEMP = 1;
public static final int THEMROSTAT_SET_POINT = 2;
private float mViewCentreX;
private float mViewCentreY;
private float mThermostatRadius;
private Canvas mCanvas;
private Paint mPaint;
private Paint mPaintCurTemp;
private Paint mPaintSetTemp;
private Paint mPaintOverrideTemp;
private Paint mPaintCurTempIndicator;
private Boolean mManualOverride = false;
private double mManualOverrideAngle;
private int mMaxTemp = 420;
private int mMinTemp = 120;
private RectF mCurrTempBox;
private float mCurTempCircleX;
private float mCurTempCircleY;
private Matrix mMatrix;
public double getManualOverrideAngle() {
return mManualOverrideAngle;
}
public void setManualOverrideAngle(double mManualOverrideAngle) {
this.mManualOverrideAngle = mManualOverrideAngle;
}
public RectF getCurrTempBox() {
if (mCurrTempBox == null){
mCurrTempBox = new RectF();
}
return mCurrTempBox;
}
public void setCurrTempBox(RectF mCurrTempBox) {
this.mCurrTempBox = mCurrTempBox;
}
public Boolean getManualOverride() {
return mManualOverride;
}
public void setManualOverride(Boolean mManualOverride) {
this.mManualOverride = mManualOverride;
}
public ThermoView(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Path smallCirle = new Path();
int viewWidth = getMeasuredWidth();
int viewHeight = getMeasuredHeight();
mViewCentreX = viewWidth/2;
mViewCentreY = viewHeight/2;
float paddingPercent = 0.2f;
int thermostatThickness = 20;
mThermostatRadius = (int) ((Math.min(mViewCentreX, mViewCentreY)*(1- paddingPercent)));
if (mPaint == null){
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
}
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(thermostatThickness);
mPaint.setColor(0xffff0000);
Path arcPath = new Path();
RectF container = new RectF();
container.set(mViewCentreX - mThermostatRadius, mViewCentreY - mThermostatRadius,
mViewCentreX + mThermostatRadius, mViewCentreY + mThermostatRadius);
arcPath.addArc(container, 120, 300);
canvas.drawPath(arcPath, mPaint);
int dummyCurTemp = 200;
if (mPaintCurTemp == null){
mPaintCurTemp = new Paint(Paint.ANTI_ALIAS_FLAG);
}
mPaintCurTemp.setTextAlign(Align.CENTER);
mPaintCurTemp.setTextSize(100);
canvas.drawText(String.valueOf(dummyCurTemp), mViewCentreX, mViewCentreY, mPaintCurTemp);
if (this.mManualOverride == false){
double angle = (360-120-(300/(mMaxTemp - mMinTemp))*(dummyCurTemp-mMinTemp))*(Math.PI/180);
this.mCurTempCircleX = (float) (mViewCentreX + mThermostatRadius*(Math.cos(angle)));
this.mCurTempCircleY = (float) (mViewCentreY - mThermostatRadius*(Math.sin(angle)));
if (mCurrTempBox == null){
mCurrTempBox = new RectF();
}
if (mPaintCurTempIndicator == null){
mPaintCurTempIndicator = new Paint(Paint.ANTI_ALIAS_FLAG);
}
mPaintCurTempIndicator.setStyle(Paint.Style.STROKE);
mPaintCurTempIndicator.setStrokeWidth(thermostatThickness/2);
mPaintCurTempIndicator.setColor(Color.GREEN);
mCurrTempBox.set(mCurTempCircleX-50, mCurTempCircleY-50, mCurTempCircleX+50, mCurTempCircleY+50);
smallCirle.addCircle(mCurTempCircleX, mCurTempCircleY, 50, Direction.CW);
canvas.drawPath(smallCirle, mPaintCurTempIndicator);
}else{
if (mCurrTempBox == null){
mCurrTempBox = new RectF();
}
if (mPaintCurTempIndicator == null){
mPaintCurTempIndicator = new Paint(Paint.ANTI_ALIAS_FLAG);
}
if (mMatrix == null){
mMatrix = new Matrix();
}
//mMatrix.reset();
mMatrix.postRotate((float) (mManualOverrideAngle), mViewCentreX,mViewCentreY);
//mMatrix.postTranslate(mViewCentreX, mViewCentreY);
mPaintCurTempIndicator.setStyle(Paint.Style.STROKE);
mPaintCurTempIndicator.setStrokeWidth(thermostatThickness/2);
mPaintCurTempIndicator.setColor(Color.GREEN);
canvas.concat(mMatrix);
smallCirle.addCircle(mCurTempCircleX, mCurTempCircleY, 50, Direction.CW);
canvas.drawPath(smallCirle, mPaintCurTempIndicator);
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mInitialX = event.getX();
mInitialY = event.getY();
RectF touchedAt = new RectF(mInitialX-10, mInitialY-10, mInitialX+10, mInitialY+10);
RectF indicatorAt = mThermoStatView.getCurrTempBox();
if (RectF.intersects(indicatorAt, touchedAt)){
this.isIndicatorSelected = true;
mThermoStatView.setManualOverride(true);
}
break;
case MotionEvent.ACTION_MOVE:
if (this.isIndicatorSelected == true){
float angle = (float) (180*Math.atan2(event.getY() - mThermostatHeight/2, event.getX() - mThermostatWidth/2) / Math.PI);
mThermoStatView.setManualOverrideAngle(angle);
mThermoStatView.invalidate();
//mThermoStatView.requestLayout();
}
break;
case MotionEvent.ACTION_UP:
if (this.isIndicatorSelected == true){
this.isIndicatorSelected = false;
}
break;
}
return true;
}
}
try this (this is a little modified version of MyView i already posted as an answer for your previous question):
public class MyView extends View {
private final static String TAG = "Main.MyView";
private static final float CX = 0;
private static final float CY = 0;
private static final float RADIUS = 20;
private static final float BIGRADIUS = 50;
private static final int NORMAL_COLOR = 0xffffffff;
private static final int PRESSED_COLOR = 0xffff0000;
private Paint mPaint;
private Path mSmallCircle;
private Path mCircle;
private Matrix mMatrix;
private float mAngle;
private int mSmallCircleColor;
public MyView(Context context) {
super(context);
mPaint = new Paint();
mSmallCircle = new Path();
mSmallCircle.addCircle(BIGRADIUS + RADIUS + CX, CY, RADIUS, Direction.CW);
mSmallCircleColor = NORMAL_COLOR;
mCircle = new Path();
mCircle.addCircle(0, 0, BIGRADIUS, Direction.CW);
mMatrix = new Matrix();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
if (action == MotionEvent.ACTION_UP) {
mSmallCircleColor = NORMAL_COLOR;
invalidate();
return false;
}
float w2 = getWidth() / 2f;
float h2 = getHeight() / 2f;
float r = 0;
if (action == MotionEvent.ACTION_DOWN) {
float[] pts = {
BIGRADIUS + RADIUS + CX, CY
};
mMatrix.mapPoints(pts);
r = (float) Math.hypot(event.getX() - pts[0], event.getY() - pts[1]);
}
if (r < RADIUS) {
mSmallCircleColor = PRESSED_COLOR;
mAngle = (float) (180 * Math.atan2(event.getY() - h2, event.getX() - w2) / Math.PI);
invalidate();
return true;
}
return false;
}
#Override
protected void onDraw(Canvas canvas) {
float w2 = getWidth() / 2f;
float h2 = getHeight() / 2f;
mMatrix.reset();
mMatrix.postRotate(mAngle);
mMatrix.postTranslate(w2, h2);
canvas.concat(mMatrix);
mPaint.setColor(0x88ffffff);
canvas.drawPath(mCircle, mPaint);
mPaint.setColor(mSmallCircleColor);
canvas.drawPath(mSmallCircle, mPaint);
}
}
You can get the rectangle of your touch point and the rectangle(position) of your inner circle and check if they cross over with the Intersects method.
http://docs.oracle.com/javase/7/docs/api/java/awt/Rectangle.html#intersects(java.awt.Rectangle)
Your canvas onTouchListener can do whatever it needs to do if the touchpoint intersect your circle.
e.g:
// Create a rectangle from the point of touch
Rect touchpoint = new Rect(x,y,10,10);
// Create a rectangle from the postion of the circle.
Rect myCircle=new Rect(10,10,20,20);
if (Rect.intersects(myCircle,touchpoint)){
Log.d("The circle was touched");
}