I use drawLines() on my dataset of points. It's drawn perfectly when it starts from (0,0), but when the dataset starts from another point it produces some gaps.
Here the chart starting with (0, 0) (added small line at left bottom):
Here it starts from from (83, 56) and produces gap:
What I've tried:
Setting on/off anti-alias.
Different datasets (they all produce gap at the top y point if there is nothing drawn at (0, 0).
I've read about trying drawPath(), but since I need to draw lots of lines it was said to be not as effecient as drawLines().
Here are some snippets from my project:
My dataset:
x = {
0,12,83,84,84,121,121,128,128,151,151,173,173,203,203,217,217,224,224,229,229,253,253,294,294,305,305,331,331,355,355,364,364,409,409,411,411,416,416,431,431,448,448,497,497,504,504,508,508,536,536,582,582,586,586,630,630,646,646,660,660,689,689,728,728,761,761,768,768,798,798,822,822,860,860,894,894,908,908,952,952,996,996,1039,1039,1085,1085,1085,1085,1099,1099,1119,1119,1133,1133,1169
}
y = {
0,12,56,115,115,220,220,232,232,170,170,350,350,117,117,157,157,205,205,290,290,184,184,127,127,181,181,231,231,210,210,278,278,142,142,120,120,299,299,29,29,290,290,50,50,258,258,127,127,203,203,168,168,27,27,27,27,83,83,116,116,228,228,295,295,62,62,299,299,121,121,216,216,266,266,164,164,234,234,116,116,182,182,130,130,208,208,218,218,202,202,85,85,59,59,114
}
How I set my Paint:
private void init() {
chartPaint = new Paint();
chartPaint.setStyle(Paint.Style.STROKE);
chartPaint.setStrokeWidth(4);
chartPaint.setColor(color);
}
My onDraw():
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.save();
// let chart start from the most left without gaps
canvas.translate(0, viewHeight);
// TODO: find place to move calcs outside onDraw()
final float xScale = (float) viewWidth / (Util.getMax(x) - Util.getMin(x));
final float yScale = (float) -viewHeight / (Util.getMax(y) - Util.getMin(y));
valuesScaled = new float[values.length];
for (int i = 0; i < values.length; i++) {
valuesScaled[i] = (i%2==0) ? values[i] * xScale : values[i] * yScale;
}
canvas.drawLines(valuesScaled, chartPaint);
canvas.restore();
}
values array is where x and y arrays are stored alternatively, i.e. first 4 elements of values are {x[0], y[0], x[1], y[1], ...}
viewWidth and viewHeight are taken from onSizeChange().
I know that creating objects inside the onDraw method is very costly. I want to draw a matrix of rounded rectangles, which coordinates are dynamic, and I can't cache all that rectangles, because I use a scroll view and there may be a lot of rectangles, there's no other overload for drawRoundRect method, which has primitive arguments, and I forced to create a Rectangle object in every iteration. Who can suggest an effective solution for that?
#Override
protected void onDraw(Canvas canvas) {
int h = getMeasuredHeight();
int tileSize = h / rows;
for(int i = 0; i < rows; ++i) {
for(int j = 0; j < columns; ++j) {
int x = j * tileSize;
int y = i * tileSize;
canvas.drawRoundRect(new RectF(x, y, x + tileSize, y + tileSize), 10, 10, tilePaint);
}
}
}
This is a just an example, rectangles can have arbitrary coordinates.
RectF has the set(left, top, right, bottom) method. You could allocate it on the constructor and it this method to change the Rectf's bounds.
mRect.set(x, y, x + tileSize, y + tileSize);
where mRect is RectF mRect = new RectF();
I'd like to be able to create an arbitrary input for time into a standard Android animation. Instead of an animation running for 1 second, I want for instance the input to be a coordinate from user touch input. This way I could for instance create a circle motion of object A when the position in the circular motion is defined by a linear input on slide A.
Crude illustration:
Now I'm thinking this could be achieved with defining the translation animation in XML just as with regular animations under /res/anim, but overriding the time input to come from a user input control instead. It minght also be done with a custom interpolator, I'm not sure. I don't what a set start and end time of the animation, in any case.
Anyone have any suggestions on how to achieve this?
edit: To further answer a couple of the comments: Think if it as the user slides/drags the blue dot. No interpolation between the input occurs. As soon as the user lifts the finger, the "animation" stops.
If I understand correctly you need some sort of 'rigging' - Defining a movement of one element as a function of another. In your case this function needs to transform the the linear position into a circular position.
There is no animation involved - When the user moves the blue circle, the red one is moved accordingly.
You should register for callbacks for the blue circle movement (i.e. onTouchEvent, or a seekBar's on change, depending on how you implement your 'bar'). Then you calculate the new position of the red circle and then you put it there.
Here's a simple working example of a custom view that draws two circles according to a given percentValue. I tested using s simple SeekBar and it works:
public class CanvasView extends View {
private int centerX = 0;
private int centerY = 0;
private int radius = 0;
private final int handleRadius = 25;
private final Paint circlePaint = new Paint();
private final Paint handlePaint = new Paint();
private float percentValue = 0f;
public CanvasView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public CanvasView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CanvasView(Context context) {
super(context);
init();
}
private void init() {
circlePaint.setColor(Color.BLACK);
handlePaint.setColor(Color.RED);
}
// Call this whenever the value of that linear bar is changed - so when the user moves his finger etc.
public void setValue(float percentage) {
this.percentValue = percentage;
invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// this is the main circle
canvas.drawCircle(centerX, centerY, radius, circlePaint);
// calculate the angle based on the percentage of the linear movement (substracting (pi/2) so the zero value is on top)
double angle = (percentValue / 100) * (2 * Math.PI) - Math.PI / 2;
// sin and cos to calculate the position of the smaller circle - the 'handle'
float handleX = centerX + (float) (radius * Math.cos(angle));
float handleY = centerY + (float) (radius * Math.sin(angle));
// drawing the circle
canvas.drawCircle(handleX, handleY, handleRadius, handlePaint);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// choose whatever values you want here, based on the view's size:
centerX = w / 2;
centerY = h / 2;
radius = w / 3;
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a triangle image whose one edge is always in the same direction as the circle.
This image has to be moved around the circle based on user swipe/drag. So, it has to both rotate (so that it's edge is in same direction as the circle) and at the same time revolve around the circle.
How to implement this feature?
UPDATE: My custom View is as follows:
public class ThermoView extends FrameLayout{
private ImageView mThermoBgrd;
private ImageView mCurTempArrow;
public static final int THEMROSTAT_BACKGROUND = 0;
public static final int THEMROSTAT_CURR_TEMP = 1;
public ThermostatView(Context context, AttributeSet attrs) {
super(context, attrs);
mThermoBgrd = new ImageView(context);
mThermoBgrd.setImageResource(R.drawable.circle_icon);
addView(mThermoBgrd, ThermostatView.THEMROSTAT_BACKGROUND);
mCurTempArrow = new ImageView(context);
mCurTempArrow.setImageResource(R.drawable.ruler_triangle_icon);
mCurTempArrow.setScaleType(ImageView.ScaleType.MATRIX);
addView(mCurTempArrow, ThermostatView.THEMROSTAT_CURR_TEMP, new LayoutParams(50, 50));
}
#Override
protected void onLayout(boolean changed, int left, int top, int right,
int bottom) {
super.onLayout(changed, left, top, right, bottom);
int currTempHeight = mCurTempArrow.getMeasuredHeight();
int currTempWidth = mCurTempArrow.getMeasuredWidth();
int parentWidth = right - left;
int parentHeight = bottom - top;
int padding = currTempHeight;
//We need square container for the circle.
int containerLeft = padding;
int containerTop = parentHeight - parentWidth + padding;
int containerRight = parentWidth - padding;
int containerBottom = parentHeight - padding;
int containerWidth = containerRight - containerLeft;
int containerHeight = containerBottom - containerTop;
//place the arrow indicating current temperature
int curTempLeft = containerRight - ((containerWidth/2) + currTempWidth/2);
int curTempTop = containerTop - (currTempHeight/2);
int curTempRight = curTempLeft + currTempWidth;
int curTempBottom = curTempTop + currTempHeight;
mCurTempArrow.layout(curTempLeft, curTempTop, curTempRight, curTempBottom);
}
try this (it uses Paths instead of Bitmaps but the idea is the same):
public class MyView extends View {
private Paint mPaint;
private Path mTriangle;
private Path mCircle;
private Matrix mMatrix;
private float mAngle;
public MyView(Context context) {
super(context);
mPaint = new Paint();
mPaint.setStrokeWidth(10);
mPaint.setStyle(Style.STROKE);
mTriangle = new Path();
mTriangle.moveTo(0, -21);
mTriangle.lineTo(0, 21);
mTriangle.lineTo(36, 0);
mTriangle.close();
mCircle = new Path();
mCircle.addCircle(0, 0, 50, Direction.CW);
mMatrix = new Matrix();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float w2 = getWidth() / 2f;
float h2 = getHeight() / 2f;
mAngle = (float) (180 * Math.atan2(event.getY() - h2, event.getX() - w2) / Math.PI);
invalidate();
return true;
}
#Override
protected void onDraw(Canvas canvas) {
float w2 = getWidth() / 2f;
float h2 = getHeight() / 2f;
mMatrix.reset();
mMatrix.postTranslate(w2, h2);
canvas.concat(mMatrix);
mPaint.setColor(0xaaff0000);
canvas.drawPath(mCircle, mPaint);
mMatrix.reset();
mMatrix.postTranslate(60, 0);
mMatrix.postRotate(mAngle);
canvas.concat(mMatrix);
mPaint.setColor(0xaa00ff00);
canvas.drawPath(mTriangle, mPaint);
}
}
Since I don't know if you are using open GL or a standard canevas, I can't really give you some working code. But the general idea is (assuming you have the current position of the triangle (x, y) stored, and the center of your circle (cx, cy) stored.
Do the following:
v = (cx-x, cy-y) // v is the normal vector of your triangle: it faces the center of the circle
triangle.translate(v) // translate to the center of the circle
triangle.rotate(angle) // rotate the triangle on itself
v.rotate(angle) // apply the same rotation on the normal vector
triangle.translate(-v) // translate back on the circle, but since v is rotated, the position will be updated
I hope it is clear enough, good luck
EDIT:
First, you should really try to be more accurate: in your first post, you didn't say that the triangle was an image (that's important). Then you don't say what is your current rendering, what works, what doesn't. I would be easier to help you to know what your program currently display.
From your code, I assume you place the triangle image properly , but it is not rotated. So first, try to add
//place the arrow indicating current temperature
int curTempLeft = containerRight - ((containerWidth/2) + currTempWidth/2);
int curTempTop = containerTop - (currTempHeight/2);
int curTempRight = curTempLeft + currTempWidth;
int curTempBottom = curTempTop + currTempHeight;
mCurTempArrow.setRotate(angle); // rotate the image. angle is in degrees
mCurTempArrow.layout(curTempLeft, curTempTop, curTempRight, curTempBottom);
If you don't know the angle, you might have to compute it from the previous position of the triangle
I have worked on pie chart in android. I found an excellent solution from http://tutorials-android.blogspot.in/2011/05/how-create-pie-chart-in-android.html and worked on that. I am able to display the pie chart with colors but in my application in addition to colors I need to display the text also dynamically on that pie chart. How can I display text dynamically on those pie chart slices?
Please help me regarding this...Will be thankful...
To draw piechart you had use very long process.....Hope this help you..
public class Demo extends Activity {
/** Called when the activity is first created. */
float values[]={500,400,300,200,100};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout linear=(LinearLayout) findViewById(R.id.linear);
values=calculateData(values);
linear.addView(new MyGraphview(this,values));
}
private float[] calculateData(float[] data) {
// TODO Auto-generated method stub
float total=0;
for(int i=0;i<data.length;i++)
{
total+=data[i];
}
for(int i=0;i<data.length;i++)
{
data[i]=360*(data[i]/total);
}
return data;
}
public class MyGraphview extends View
{
private Paint paint=new Paint(Paint.ANTI_ALIAS_FLAG);
private float[] value_degree;
private int[] COLORS={Color.BLUE,Color.GREEN,Color.GRAY,Color.CYAN,Color.RED};
RectF rectf = new RectF (10, 10, 200, 200);
int temp=0;
public MyGraphview(Context context, float[] values) {
super(context);
value_degree=new float[values.length];
for(int i=0;i<values.length;i++)
{
value_degree[i]=values[i];
}
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
for (int i = 0; i < value_degree.length; i++) {//values2.length; i++) {
if (i == 0) {
paint.setColor(COLORS[i]);
canvas.drawArc(rectf, 0, value_degree[i], true, paint);
}
else
{
temp += (int) value_degree[i - 1];
paint.setColor(COLORS[i]);
canvas.drawArc(rectf, temp, value_degree[i], true, paint);
}
}
}
}
}
Which set the color according to values in decending order...
And for text,you can set dynamic text separately and give color square in front of text:)
To draw text at the centre of each pie chart segment you need to calculate the centre of each segment. The centre of each text item to paint on that segment should align with that centre point - which is achieved by subtracting half the text bounds width from the central x coord (or using paint.setTextAlign(Align.CENTER); ) and half the text bound height from the central y coord.
As for finding the centre of a segment, it requires just a little bit more consideration than using simple geometry.
The central coords of a segment can be found by:
x = (/* radius of pie chart */ /2)*cos(/*angle in RADIANS */) [angle in radians = Math.toRadians(/*half the sweep angle in degrees*/)
y = (/* radius of pie chart */ /2)*sin(/*angle in RADIANS */)
Almost there... dont forget to add the x and y coords of the centre of your pie chart to the above x and y values, otherwise you're trying to paint on a circle centring on (0,0) in your custom view!
Say your pie chart is centred at the actual centre of your view, you want to be adding:
x += getWidth()/2;
y += getHeight()/2;
Last but not least, accounting for the length of the text to be painted - get the bounds of your text using, for example:
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setTextAlign(Align.CENTER); // This centres the text horizontally
String labelText = "TEST";
Rect textBounds = new Rect();
paint.getTextBounds(labelText, 0, labelText.length(), textBounds);
y -= textBounds.height()/2;
Then your text should appear correctly.
You can use the library called MPAndroidChart, which is very simple and easy to use. Simply import this
compile 'com.github.PhilJay:MPAndroidChart:v3.0.1'
and add this line in your gradle file
allprojects {
repositories {
maven { url "https://jitpack.io" }
}
}
Hope this will help you.
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mState != IS_READY_TO_DRAW) {
return;
}
canvas.drawColor(mBgcolor);
mBagpaints.setAntiAlias(true);
mBagpaints.setStyle(Paint.Style.FILL);
mBagpaints.setColor(0x88FF0000);
mBagpaints.setStrokeWidth(0.0f);
mLinePaints.setAntiAlias(true);
mLinePaints.setColor(0xff000000);
mLinePaints.setStrokeWidth(3.0f);
mLinePaints.setStyle(Paint.Style.STROKE);
RectF mOvals = new RectF(mGapleft, mGapTop, mWidth - mGapright, mHeight
- mGapBottm);
mStart = START_INC;
PieDetailsItem item;
for (int i = 0; i < mdataArray.size(); i++) {
item = (PieDetailsItem) mdataArray.get(i);
mBagpaints.setColor(item.color);
mSweep = (float) 360* ((float) item.count / (float) mMaxConnection);
canvas.drawArc(mOvals, mStart, mSweep, true, mBagpaints);
canvas.drawArc(mOvals, mStart, mSweep, true, mLinePaints);
mStart = mStart + mSweep;
// set your text here
canvas.drawText("here is some text", mStart, someYvalue, mLinePaints);
}
mState = IS_DRAW;
}
Just some drawText() calls ought to work fine.
You'll have to do a little math to decide where your y coordinate should be