Android SweepGradient and Drawing Lines in a circular pattern - android

I am trying to achieve this circular progress bar with gradient intervals UI effect
Currently I have been able to achieve this.
The code for my current implementation is below.
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.SweepGradient;
import android.graphics.drawable.AnimationDrawable;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
public class CBPDrawable extends AnimationDrawable {
Paint paint = new Paint();
RectF clip = new RectF();
LinearGradient shader;
Path path;
private static final int MAX = 360;
int dots = 75;
int dotRadius = 20;
RectF dotRect;
Context mContext;
public CBPDrawable(Context context){
mContext = context;
}
Shader gradient;
private int mTickOffset = 0;
private int mTickLength = 15;
private int mArcRadius = 10;
double slope, startTickX, startTickY, endTickX, endTickY, midTickX, midTickY, thetaInRadians;
double radiusOffset = mArcRadius + mTickOffset;
#Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
path = new Path();
dotRect = new RectF(0, 0, dotRadius, dotRadius);
/*
for (int i = 0; i < dots; ++i) {
start();
path.addRoundRect(dotRect, dotRadius, dotRadius, Path.Direction.CCW);
stop();
}
*/
for (int i = 360; i >= 0; i -= 5) {
thetaInRadians = Math.toRadians(360 - i);
slope = Math.tan(thetaInRadians);
startTickX = (radiusOffset * Math.cos(thetaInRadians));
startTickY = slope * startTickX;
endTickX = startTickX + ((mTickLength) * Math.cos(thetaInRadians));
endTickY = slope * endTickX;
RectF r = new RectF();
r.set((float) startTickX, (float) startTickY, (float) endTickX, (float) endTickY);
path.addRoundRect(r, (int)radiusOffset, (int)radiusOffset, Path.Direction.CCW);
}
}
#Override
public void draw(#NonNull Canvas canvas) {
Rect b = getBounds();
final int width = canvas.getWidth();
final int height = canvas.getHeight();
final int squareSide = Math.min(width, height);
canvas.translate(width / 2f, height / 2f); // moving to the center of the View
canvas.rotate(270);
final float outerRadius = squareSide / 2f;
final float innerRadius = outerRadius - dotRadius;
final float angleFactor = 360f / 72;
int[] colors = new int[]{Color.BLUE, Color.RED};
float[] positions = new float[]{0,0.4f};
gradient = new SweepGradient(outerRadius / 2f, outerRadius / 2f,colors,null);
for (int i = 0; i < 72; ++i) {
canvas.save(); // creating a "checkpoint"
canvas.rotate(angleFactor * i);
canvas.translate(innerRadius, 0); //moving to the edge of the big circle
clip.set(b);
paint.setColor(Color.GRAY);
if(angleFactor * i <= 200){
paint.setShader(gradient);
}else{
paint.setShader(null);
}
//canvas.clipRect(clip, Region.Op.REPLACE);
canvas.drawPath(path, paint);
canvas.restore(); //restoring a "checkpoint"
//stop();
}
}
#Override
public void setAlpha(#IntRange(from = 0, to = 255) int i) {
}
#Override
public void setColorFilter(#Nullable ColorFilter colorFilter) {
}
#Override
public int getOpacity() {
return PixelFormat.OPAQUE;
}
}
As can be seen from the 2 images, I am unable to get the intervals correctly as a rectangle or line.
And, the gradient does not show, in spite of using a SweepGradient.
How should I go about achieving the desired effect?
Thanks.

Related

How to make a square shape generate in an Android app instead of a circle

I am working on a android launcher that shows the 1st 4 app icons in a grid view however I'm trying to display the folder as a square shape it's showing up as a circle shape...
heres my code:
package appname.launcher.util;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.Region;
import android.graphics.drawable.Drawable;
import android.view.View;
import Appname.launcher.activity.Home;
public class GroupIconDrawable extends Drawable{
private int outlinepad;
Bitmap[] icons;
public int iconSize;
Paint paint;
Paint paint2;
Paint paint4;
private int iconSizeDiv2;
private int padding;
private float scaleFactor = 1;
private boolean needAnimate,needAnimatScale;
public View v;
private float sx = 1;
private float sy = 1 ;
public GroupIconDrawable(Bitmap[] icons,int size){
init(icons,size);
}
private void init(Bitmap[] icons,int size){
this.icons = icons;
this.iconSize = size;
iconSizeDiv2 = Math.round(iconSize / 2f);
padding = iconSize /25;
this.paint = new Paint();
paint.setColor(Color.WHITE);
paint.setAlpha(200);
paint.setAntiAlias(true);
this.paint4 = new Paint();
paint4.setColor(Color.WHITE);
paint4.setAntiAlias(true);
paint4.setFlags(Paint.ANTI_ALIAS_FLAG);
paint4.setStyle(Paint.Style.STROKE);
outlinepad = Tools.convertDpToPixel(2, Home.desktop.getContext());
paint4.setStrokeWidth(outlinepad);
this.paint2 = new Paint();
paint2.setAntiAlias(true);
paint2.setFilterBitmap(true);
}
public GroupIconDrawable(Bitmap[] icons,int size,View v){
init(icons,size);
this.v =v;
}
public void popUp(){
sy = 1;
sx = 1;
needAnimate = true;
needAnimatScale = true;
invalidateSelf();
}
public void popBack(){
needAnimate = false;
needAnimatScale = false;
invalidateSelf();
}
#Override
public void draw(Canvas canvas) {
canvas.save();
if (needAnimatScale){
scaleFactor = Tools.clampFloat(scaleFactor-0.09f,0.5f,1f);
}else {
scaleFactor = Tools.clampFloat(scaleFactor+0.09f,0.5f,1f);
}
if (v == null)
canvas.scale(scaleFactor,scaleFactor,iconSize/2,iconSize/2);
else
canvas.scale(scaleFactor,scaleFactor,iconSize/2,v.getHeight() / 2);
if (v!= null)
canvas.translate(0,v.getHeight()/2-iconSize/2);
Path clipp = new Path();
clipp.addCircle(iconSize / 2,iconSize / 2,iconSize / 2-outlinepad, Path.Direction.CW);
canvas.clipPath(clipp, Region.Op.REPLACE);
canvas.drawBitmap(icons[0],null,new Rect(padding,padding, iconSizeDiv2-padding, iconSizeDiv2-padding),paint2);
canvas.drawBitmap(icons[1],null,new Rect(iconSizeDiv2+padding,padding,iconSize-padding, iconSizeDiv2-padding),paint2);
canvas.drawBitmap(icons[2],null,new Rect(padding, iconSizeDiv2+padding, iconSizeDiv2-padding,iconSize-padding),paint2);
canvas.drawBitmap(icons[3],null,new Rect(iconSizeDiv2+padding, iconSizeDiv2+padding,iconSize-padding,iconSize-padding),paint2);
canvas.clipRect(0,0,iconSize,iconSize, Region.Op.REPLACE);
canvas.restore();
if (needAnimate){
paint2.setAlpha(Tools.clampInt(paint2.getAlpha()-25,0,255));
invalidateSelf();
}else if (paint2.getAlpha() != 255){
paint2.setAlpha(Tools.clampInt(paint2.getAlpha()+25,0,255));
invalidateSelf();
}
}
#Override
public void setAlpha(int i) {}
#Override
public void setColorFilter(ColorFilter colorFilter) {}
#Override
public int getOpacity() {return 0;}
}
I think its because of the > clipp.addCircle(iconSize / 2,iconSize /
2,iconSize / 2-outlinepad,> Path.Direction.CW); code but i'm not sure
how would I make it a square instead of a circle?
change your clipp Path usage from addCircle to be addRect(float left, float top, float right, float bottom, Path.Direction dir)

Android How to draw a regular polygon via xml or programical

Is there any way to draw polygonal shapes on Android xml layouts?
or is any helper class as library to draw them?
I am using enhanced version of this Class
See working sample on GitHub (https://github.com/hiteshsahu/Benzene)
Drawable Class
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
/**
* Originally Created by AnderWeb (Gustavo Claramunt) on 7/10/14.
*/
public class PolygonalDrwable extends Drawable {
private int numberOfSides = 3;
private Path polygon = new Path();
private Path temporal = new Path();
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
public PolygonalDrwable(int color, int sides) {
paint.setColor(color);
polygon.setFillType(Path.FillType.EVEN_ODD);
this.numberOfSides = sides;
}
#Override
public void draw(Canvas canvas) {
canvas.drawPath(polygon, paint);
}
#Override
public void setAlpha(int alpha) {
paint.setAlpha(alpha);
}
#Override
public void setColorFilter(ColorFilter cf) {
paint.setColorFilter(cf);
}
#Override
public int getOpacity() {
return paint.getAlpha();
}
#Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
computeHex(bounds);
invalidateSelf();
}
public void computeHex(Rect bounds) {
final int width = bounds.width();
final int height = bounds.height();
final int size = Math.min(width, height);
final int centerX = bounds.left + (width / 2);
final int centerY = bounds.top + (height / 2);
polygon.reset();
polygon.addPath(createHexagon(size, centerX, centerY));
polygon.addPath(createHexagon((int) (size * .8f), centerX, centerY));
}
private Path createHexagon(int size, int centerX, int centerY) {
final float section = (float) (2.0 * Math.PI / numberOfSides);
int radius = size / 2;
Path polygonPath = temporal;
polygonPath.reset();
polygonPath.moveTo((centerX + radius * (float)Math.cos(0)), (centerY + radius
* (float)Math.sin(0)));
for (int i = 1; i < numberOfSides; i++) {
polygonPath.lineTo((centerX + radius * (float)Math.cos(section * i)),
(centerY + radius * (float)Math.sin(section * i)));
}
polygonPath.close();
return polygonPath;
}
}
Set drawable to any Imageview like this
//Triangle
((ImageView) findViewById(R.id.triangle))
.setBackgroundDrawable(new PolygonalDrwable(Color.GREEN, 3));
//Square
((ImageView) findViewById(R.id.square))
.setBackgroundDrawable(new PolygonalDrwable(Color.MAGENTA, 4));
//Pentagon
((ImageView) findViewById(R.id.pentagon))
.setBackgroundDrawable(new PolygonalDrwable(Color.LTGRAY, 5));
//Hexagon
((ImageView) findViewById(R.id.hex))
.setBackgroundDrawable(new PolygonalDrwable(Color.RED, 6));
//Heptagon
((ImageView) findViewById(R.id.hept))
.setBackgroundDrawable(new PolygonalDrwable(Color.MAGENTA, 7));
//Octagon
((ImageView) findViewById(R.id.oct))
.setBackgroundDrawable(new PolygonalDrwable(Color.YELLOW, 8));
You can create custom drawable and shapes as drawable resources.
Right click on the "drawable" folder in Android Studio and select New->Drawable Resource File.
Here is a decent tutorial for shapes and strokes to get started.
Here is some example shapes ready to use.
Here is documentation for some more complex things you can do with drawables.

Create dropping ball

When the play button is pressed to start the game(activity), I'd like to create the instance of a ball falling from the top of the screen (the ball will hit something later). I'm not sure how to go about it. Can anyone assist?
What I'm working with so far:
public class GameActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Turn title off
requestWindowFeature(Window.FEATURE_NO_TITLE);
// set Game to fullscreen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
View ballView = new BallView(this);
setContentView(ballView);
// ballView.setBackgroundColor(Color.TRANSPARENT);
}
}
and
public class BallView extends View {
// Ball attributes
private float ballRadius = 30;
private float ballX = 50;
private float ballY = 50;
private RectF ballBounds;
private Paint ballColor;
// For game elements
private int score = 0;
public BallView(Context context){
super(context);
// Initialize game elements
ballBounds = new RectF();
ballColor = new Paint();
this.setFocusableInTouchMode(true);
}
public void onDraw(Canvas canvas){
// Draw ball
ballBounds.set(ballX - ballRadius, ballY - ballRadius, ballX + ballRadius, ballY + ballRadius);
ballColor.setColor(Color.RED);
canvas.drawOval(ballBounds, ballColor);
}
}
From the description of your intent, you should probably use OpenGL or a framework like libgdx which has physics and collision detection built in.
But to answer you question, you try this quick example:
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.view.View;
import android.view.ViewTreeObserver;
public class BallView extends View{
// Ball attributes
private float ballRadius = 30;
private float ballX = 50;
private float ballY = 50;
private float ballSpeed = 10.0f;
private RectF ballBounds;
private Paint ballColor;
boolean doBallAnimation = false;
// For game elements
private int score = 0;
ValueAnimator animator = ValueAnimator.ofFloat(0, 1);
long startTime, prevTime; // Used to track elapsed time for animations and fps
public BallView(Context context){
super(context);
// Initialize game elements
ballBounds = new RectF();
ballColor = new Paint();
this.setFocusableInTouchMode(true);
getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener(){
#Override
public void onGlobalLayout(){
getViewTreeObserver().removeOnGlobalLayoutListener(this);
ballY = 0;
ballX = (getWidth()- ballRadius) / 2.0f;
doBallAnimation = true;
animator.start();
}
}
);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener(){
#Override
public void onAnimationUpdate(ValueAnimator arg0){
long nowTime = System.currentTimeMillis();
float secs = (float)(nowTime - prevTime) / 1000f;
prevTime = nowTime;
if((ballY + ballSpeed) > (getHeight() - (ballRadius)))
{
animator.cancel();
return;
}
ballY += ballSpeed;
// Force a redraw to see the ball in its new position
invalidate();
}
});
animator.setRepeatCount(ValueAnimator.INFINITE);
animator.setDuration(3000);
}
public void onDraw(Canvas canvas){
// Draw ball
if(doBallAnimation)
{
ballBounds.set(ballX - ballRadius, ballY - ballRadius, ballX + ballRadius, ballY + ballRadius);
ballColor.setColor(Color.RED);
canvas.drawOval(ballBounds, ballColor);
}
}
}

Osmdroid. onItemSingleTapUp not works for custom Drawable

I have created custom drawable marker which uses canvas to draw
bounds. Everything works great excepts one thing: onItemSingleTapUp
not called when any marker on the screen taped.
Here is overlay creation code:
ItemizedIconOverlay<OverlayItem> groupsOverlay = new ItemizedIconOverlay<OverlayItem>(
new ArrayList<OverlayItem>(),
new OnItemGestureListener<OverlayItem>() {
#Override
public boolean onItemLongPress(int arg0, OverlayItem arg1) {
return false;
}
#Override
public boolean onItemSingleTapUp(int arg0, OverlayItem arg1) {
if(arg1 == null){
return false;
}
if(m_prevView != null){
m_mapView.removeView(m_prevView);
m_prevView = null;
}
View popUp = getLayoutInflater().inflate(R.layout.map_popup, m_mapView, false);
TextView tv = (TextView)popUp.findViewById(R.id.popupTextView);
tv.setText(arg1.getTitle());
MapView.LayoutParams mapParams = new MapView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
arg1.getPoint(),
MapView.LayoutParams.BOTTOM_CENTER, 0, 0);
m_mapView.addView(popUp, mapParams);
m_prevView = popUp;
return true;
}
}, new DefaultResourceProxyImpl(getApplicationContext()));
This is custom drawable marker:
package com.testapp.data;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
public class GroupMarkerDrawable extends Drawable {
private final static int DELTA_BOX = 4;
private final Paint m_paint;
private String m_text;
private double m_pxRadius;
public GroupMarkerDrawable(double pxRadius, String text) {
m_text = text;
m_paint = new Paint();
m_pxRadius = pxRadius;
m_paint.setAntiAlias(true);
}
#Override
public void draw(Canvas c) {
// Set the correct values in the Paint
m_paint.setARGB(190, 0, 0, 0);
m_paint.setStrokeWidth(2);
m_paint.setStyle(Style.STROKE);
m_paint.setTextAlign(Align.CENTER);
Rect bounds = new Rect();
m_paint.getTextBounds(m_text, 0, m_text.length(), bounds);
int centerX = getBounds().centerX();
int centerY = getBounds().centerY();
int w2 = bounds.width() / 2;
int h2 = bounds.height() / 2;
Rect rect = new Rect(centerX - w2 - DELTA_BOX, centerY - h2 -
DELTA_BOX, centerX + w2 + DELTA_BOX, centerY + h2 + DELTA_BOX);
// Draw it
c.drawCircle(centerX, centerY, (float) m_pxRadius, m_paint);
m_paint.setStyle(Style.FILL);
m_paint.setARGB(190, 0, 128, 0);
c.drawRect(rect, m_paint);
m_paint.setStyle(Style.STROKE);
m_paint.setARGB(190, 0, 0, 0);
c.drawRect(rect, m_paint);
c.drawText(m_text, centerX, centerY + h2, m_paint);
}
#Override
public int getOpacity() {
return PixelFormat.OPAQUE;
}
#Override
public void setAlpha(int arg0) {
}
#Override
public void setColorFilter(ColorFilter arg0) {
}
}
Same code using static drawable from resources, instead of
GroupMarkerDrawable, works.
I found how to solve this. Just need to return proper dimensions for Drawable. This requires overriding of two methods in GroupMarkerDrawable. FOr example like this:
#Override
public int getIntrinsicHeight() {
return m_pxRadius * 2;
};
#Override
public int getIntrinsicWidth() {
return m_pxRadius * 2;
};
An additional solution for a polygon.
The solutions of ydanila put me on the good track but I had to override hitTest method of ItemizedOverlayWithFocus class in order to get my polygon hit.
Drawable:
Drawable drawable = new Drawable() {
private int mIntrinsicHeight = 0;
private int mIntrinsicWidth = 0;
#Override
public void draw(Canvas canvas) {
// used to determine limit coordinates of the drawable
int yTop, yBottom, xLeft, xRight;
if (points != null && points.size() > 1) {
//we have to make a projection to convert from postions on the map in
//gradiant to a position on the view in pixels
final Projection pj = mapView.getProjection();
Path path = new Path();
Point centerMapPixelPoint = new Point();
Point tmpMapPixelPoint = new Point();
pj.toMapPixels(points.get(0), centerMapPixelPoint);
// init limit coordinates
xLeft = centerMapPixelPoint.x;
xRight = centerMapPixelPoint.x;
yTop = centerMapPixelPoint.y;
yBottom = centerMapPixelPoint.y;
path.moveTo(centerMapPixelPoint.x, centerMapPixelPoint.y);
for (int i = 1; i < points.size(); i++) {
pj.toMapPixels(points.get(i), tmpMapPixelPoint);
// update limit coordinates if necessary
if (xLeft > tmpMapPixelPoint.x) {
xLeft = tmpMapPixelPoint.x;
}
if (xRight < tmpMapPixelPoint.x) {
xRight = tmpMapPixelPoint.x;
}
if (yBottom < tmpMapPixelPoint.y) {
yBottom = tmpMapPixelPoint.y;
}
if (yTop > tmpMapPixelPoint.y) {
yTop = tmpMapPixelPoint.y;
}
path.lineTo(tmpMapPixelPoint.x, tmpMapPixelPoint.y);
}
// close polygon returning to first point
path.close();
canvas.drawPath(path, linePaint);
canvas.drawPath(path, innerPaint);
// calculate drawable height and width
mIntrinsicHeight = yTop -yBottom;
mIntrinsicWidth = xRight - xLeft;
}
}
#Override
public int getIntrinsicHeight() {
return mIntrinsicHeight;
};
#Override
public int getIntrinsicWidth() {
return mIntrinsicWidth;
};
};
Overlay:
public class MyItemizedIconOverlay<Item extends OverlayItem> extends ItemizedOverlayWithFocus<Item> {
#Override
protected boolean hitTest(Item item, Drawable marker, int hitX, int hitY) {
boolean hit = false;
Rect bounds = marker.getBounds();
if (hitX < bounds.right && hitX > bounds.left && hitY < bounds.top && hitY > bounds.bottom) {
hit = true;
} else {
hit = false;
}
return hit;
};

Android Progressbar with circle radius changes Dynamically

I want to change the circle radius dependent on the slider position
I created both individually.
while apply the circle method to the the Progress bar.
facing error.
Actually I call the Progress-Bar(Seek Bar) with
setContentView(R.layout.main);
and for drawing circle as you know I have to used setContentView(demoview);
Query: I want to merge both layout as display into image.
I didn't have idea will it possible or not?
Any guidance,tutorial appreciable.
Thanks for give your valuable time for my query.
Hope you have solution.
Check this out..
I am not using android seekbar, instead i am drawing a similar seekbar on canvas..
Check if this code can help u..
package com.test;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public class SampleComp extends View implements OnTouchListener {
private Paint paint = null;
private int width = 0;
private int height = 0;
private int barStartX = 20;
private int barStartY = 20;
private int barEndX;
private int barEndY = 30;
private int radius;
private int heightAvailableForCircle;
private int widthAvailableForCircle;
private int maxRadius;
private int totalSeekBarLength;
private int currentSeekBarLength = 10;
private int whatPercentOfSeekBarIsSelected = 50;
public SampleComp(Context context) {
super(context);
paint = new Paint();
paint.setAntiAlias(true);
setOnTouchListener(this);
}
public SampleComp(Context context, AttributeSet attrs) {
super(context, attrs);
paint = new Paint();
paint.setAntiAlias(true);
}
public SampleComp(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
paint = new Paint();
paint.setAntiAlias(true);
}
#Override
public void onDraw(Canvas canvas){
barEndX = getWidth() - 20;
paint.setColor(Color.WHITE);
setWidth(canvas.getWidth());
setHeight(canvas.getHeight());
setHeightAvailableForCircle(getViewHeight() - barEndY);
setWidthAvailableForCircle(getViewWidth() - 40);
System.out.println("heightAvailableForCircle: "+getAvailableHeightForCircle());
System.out.println("widthAvailableForCircle: "+getWidthAvailableForCircle());
totalSeekBarLength = barEndX - barStartX;
System.out.println("SEEK LEN: "+totalSeekBarLength);
canvas.drawRect(barStartX, barStartY, barEndX, barEndY, paint);
paint.setColor(Color.BLUE);
setMaxRadius(heightAvailableForCircle, widthAvailableForCircle);
whatPercentOfSeekBarIsSelected = getSelectedSeekBarPercentage(totalSeekBarLength,getCurrentSeekBarLenghtSelected());
System.out.println("whatPercentOfSeekBarIsSelected: "+whatPercentOfSeekBarIsSelected);
System.out.println("!!!!!: "+canvas.getWidth());
System.out.println("####: "+getViewWidth());
System.out.println("^^^^^^^^^************: "+ (whatPercentOfSeekBarIsSelected * (getViewWidth() - 40)) / 100);
canvas.drawRect(barStartX, barStartY, ( (whatPercentOfSeekBarIsSelected * (getViewWidth() - 40)) / 100) + 20,
barEndY, paint);
paint.setColor(Color.GRAY);
setRadius(whatPercentOfSeekBarIsSelected);
canvas.drawCircle( (canvas.getWidth())/2, (canvas.getHeight() - 30)/2, radius, paint);
}
private void setRadius(int per){
this.radius = (getMaxRadius() * per)/100;
}
private int getSelectedSeekBarPercentage(int total, int current){
int per = 0;
per = ( (current * 100) / total);
return per;
}
private void setRadius(int total, int current){
System.out.println("total: "+total);
System.out.println("current: "+current);
this.radius = ( ( (getMaxRadius()/2) * current) / 100);
System.out.println("radius: "+this.radius);
}
private void setMaxRadius(int h, int w){
this.maxRadius = h < w ? h/2 : w/2 ;
}
private int getMaxRadius(){
return this.maxRadius;
}
private void setWidth(int w){
this.width = w;
}
private void setHeight(int h){
this.height = h;
}
private int getViewWidth(){
return this.width;
}
private int getViewHeight() {
return this.height;
}
private void setHeightAvailableForCircle(int availableHeightForCircle){
this.heightAvailableForCircle = availableHeightForCircle;
}
private int getAvailableHeightForCircle(){
return this.heightAvailableForCircle;
}
private void setWidthAvailableForCircle(int wid){
this.widthAvailableForCircle = wid;
}
private int getWidthAvailableForCircle(){
return this.widthAvailableForCircle;
}
private void setCurrentSeekBarLength(int x){
this.currentSeekBarLength = x;
}
private int getCurrentSeekBarLenghtSelected(){
return this.currentSeekBarLength;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
System.out.println("x: "+x);
System.out.println("y: "+y);
if(x >= 10 && x<= barEndX && y >= 10 && y <= 30){
System.out.println("TRUE");
setCurrentSeekBarLength(x - 20);
invalidate();
}
return false;
}
}
And this is my Activity class:
package com.test;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.widget.ImageView;
public class SampleActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new SampleComp(this));
}
}
Can u be little more specific regarding what u want to achieve. Ur question isn't that clear. What i can make out is, u want to increase/decrease the radius of the circle based on the progress bar value.
Have a look at the android custom component guide. You basically have to derive your circle component from android.view.View. Then you can add it to your layout like every other component.

Categories

Resources