This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
I have used to draw pie chart using canvas..
There are approximately 10 arcs in pie chart..i want to perform click event on each arc.
Is there any way to do this? or any other way?
This is my pie chart view..
MyView.java
package android.piechart;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
public class MyView extends View {
private Paint p;
private int startX;
private int startY;
private int radius;
private ArrayList<Integer> colors;
private ArrayList<Integer> values;
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
p = new Paint();
p.setColor(Color.BLUE);
p.setAntiAlias(true);
colors = new ArrayList<Integer>();
values = new ArrayList<Integer>();
startX = 320 / 4;
startY = 480 / 8;
radius = 320 / 2;
colors.add(Color.GREEN);
colors.add(Color.CYAN);
colors.add(Color.MAGENTA);
colors.add(Color.BLUE);
colors.add(Color.RED);
values.add(0);
values.add(1);
values.add(3);
values.add(0);
values.add(2);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Log.e("", "onDraw() is called...");
float offset = 0;
float sum = 0;
for (int a = 0; a < values.size(); a++) {
sum += values.get(a);
}
float angle = (float) (360 / sum);
Log.e("angle", "" + angle);
RectF rectF = new RectF();
rectF.set(getStartX(), getStartY(), getStartX() + getRadius(),
getStartY() + getRadius());
for (int i = 0; i < values.size(); i++) {
p.setColor(colors.get(i));
if (i == 0) {
canvas.drawArc(rectF, 0, values.get(i) * angle, true, p);
} else {
canvas.drawArc(rectF, offset, values.get(i) * angle, true, p);
}
offset += (values.get(i) * angle);
}
canvas.save();
}
public int getStartX() {
return startX;
}
public void setStartX(int startX) {
this.startX = startX;
}
public int getStartY() {
return startY;
}
public void setStartY(int startY) {
this.startY = startY;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
public ArrayList<Integer> getColors() {
return colors;
}
public void setColors(ArrayList<Integer> colors) {
this.colors = colors;
}
public ArrayList<Integer> getValues() {
return values;
}
public void setValues(ArrayList<Integer> values) {
this.values = values;
}
}
Thanks in advance..
I solved my question myself...
MyView.java
public class MyView extends View {
private Paint p;
private int startX;
private int startY;
private int radius;
private ArrayList<Integer> colors;
private ArrayList<Float> values;
Bitmap bitmap;
Context mContext;
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
p = new Paint();
p.setAntiAlias(true);
colors = new ArrayList<Integer>();
values = new ArrayList<Float>();
startX = 320 / 4;
startY = 480 / 8;
radius = 320 / 2;
colors.add(Color.GREEN);
colors.add(Color.CYAN);
colors.add(Color.MAGENTA);
colors.add(Color.BLUE);
colors.add(Color.RED);
values.add(5f);
values.add(1f);
values.add(3f);
values.add(5f);
values.add(2f);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
bitmap = Bitmap.createBitmap(canvas.getWidth(), canvas.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
Log.e("", "onDraw() is called...");
float offset = 0;
float sum = 0;
for (int a = 0; a < values.size(); a++) {
sum += values.get(a);
}
float angle = (float) (360 / sum);
Log.e("angle", "" + angle);
RectF rectF = new RectF();
rectF.set(getStartX(), getStartY(), getStartX() + getRadius(),
getStartY() + getRadius());
for (int i = 0; i < values.size(); i++) {
p.setColor(colors.get(i));
if (i == 0) {
canvas.drawArc(rectF, 0, values.get(i) * angle, true, p);
c.drawArc(rectF, 0, values.get(i) * angle, true, p);
} else {
canvas.drawArc(rectF, offset, values.get(i) * angle, true, p);
c.drawArc(rectF, offset, values.get(i) * angle, true, p);
}
offset += (values.get(i) * angle);
}
canvas.save();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
int color = bitmap.getPixel((int) event.getX(), (int) event.getY());
Log.e("", "" + color);
if (colors.contains(color)) {
Log.e("", "is matching");
if (color == Color.RED) {
Toast.makeText(mContext, "Is Red", Toast.LENGTH_SHORT).show();
}
if (color == Color.CYAN) {
Toast.makeText(mContext, "Is Cyan", Toast.LENGTH_SHORT).show();
}
if (color == Color.MAGENTA) {
Toast.makeText(mContext, "Is MAGENTA", Toast.LENGTH_SHORT)
.show();
}
if (color == Color.BLUE) {
Toast.makeText(mContext, "Is BLUE", Toast.LENGTH_SHORT).show();
}
if (color == Color.GREEN) {
Toast.makeText(mContext, "Is GREEN", Toast.LENGTH_SHORT).show();
}
}
return super.onTouchEvent(event);
}
public int getStartX() {
return startX;
}
public void setStartX(int startX) {
this.startX = startX;
}
public int getStartY() {
return startY;
}
public void setStartY(int startY) {
this.startY = startY;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
public ArrayList<Integer> getColors() {
return colors;
}
public void setColors(ArrayList<Integer> colors) {
this.colors = colors;
}
public ArrayList<Float> getValues() {
return values;
}
public void setValues(ArrayList<Float> values) {
this.values = values;
}
}
I hope it's useful to others...
piechart
If you've used a Canvas, you probably have a reference to its underlying Bitmap. You could use Bitmap.getPixel(int x, int y) and test the color it returns to decide which section the click was in.
Otherwise, you have to do the calculation manually to figure out which wedge contains the x,y coordinates of your click.
Related
I wanted to draw on the canvas with the code below with my custom brush, but as you can see in the picture, the background of my brush is black, albeit without color.
Although I specified the brush color as Color.TRANSPARENT or Color.parseColor ("# 00000000"), the brush background still turns black.
How can I make the background color of my brush transparent?
click to see the picture
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import androidx.annotation.ColorInt;
import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
import android.util.AttributeSet;
import android.util.Pair;
import android.view.MotionEvent;
import android.view.View;
import java.util.Stack;
public class BrushDrawingView extends View {
static final float DEFAULT_BRUSH_SIZE = 50.0f;
static final float DEFAULT_ERASER_SIZE = 50.0f;
static final int DEFAULT_OPACITY = 255;
private float mBrushSize = DEFAULT_BRUSH_SIZE;
private float mBrushEraserSize = DEFAULT_ERASER_SIZE;
private int mOpacity = DEFAULT_OPACITY;
private final Stack<BrushLinePath> mDrawnPaths = new Stack<>();
private final Stack<BrushLinePath> mRedoPaths = new Stack<>();
private final Paint mDrawPaint = new Paint();
private Canvas mDrawCanvas;
private boolean mBrushDrawMode;
private Bitmap brushBitmap;
private Path mPath;
private float mTouchX, mTouchY;
private static final float TOUCH_TOLERANCE = 4;
private BrushViewChangeListener mBrushViewChangeListener;
public BrushDrawingView(Context context) {
this(context, null);
}
public BrushDrawingView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public BrushDrawingView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setupBrushDrawing();
}
private void setupBrushDrawing() {
//Caution: This line is to disable hardware acceleration to make eraser feature work properly
setupPathAndPaint();
setVisibility(View.GONE);
}
private void setupPathAndPaint() {
mPath = new Path();
mDrawPaint.setAntiAlias(true);
mDrawPaint.setStyle(Paint.Style.STROKE);
mDrawPaint.setStrokeJoin(Paint.Join.ROUND);
mDrawPaint.setStrokeCap(Paint.Cap.ROUND);
mDrawPaint.setStrokeWidth(mBrushSize);
mDrawPaint.setAlpha(mOpacity);
}
private void refreshBrushDrawing() {
mBrushDrawMode = true;
setupPathAndPaint();
}
void brushEraser() {
mBrushDrawMode = true;
mDrawPaint.setStrokeWidth(mBrushEraserSize);
mDrawPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
}
public void setBrushDrawingMode(boolean brushDrawMode) {
this.mBrushDrawMode = brushDrawMode;
if (brushDrawMode) {
this.setVisibility(View.VISIBLE);
refreshBrushDrawing();
}
}
public Bitmap getBrushBitmap() {
return brushBitmap;
}
public void setBrushBitmap(Bitmap brushBitmap) {
this.brushBitmap = brushBitmap;
}
public void setOpacity(#IntRange(from = 0, to = 255) int opacity) {
this.mOpacity = (int) (opacity * 2.55f);
setBrushDrawingMode(true);
}
public int getOpacity() {
return mOpacity;
}
boolean getBrushDrawingMode() {
return mBrushDrawMode;
}
public void setBrushSize(float size) {
mBrushSize = 5 + (int) (size);
setBrushDrawingMode(true);
}
void setBrushColor(#ColorInt int color) {
mDrawPaint.setColor(color);
setBrushDrawingMode(true);
}
void setBrushEraserSize(float brushEraserSize) {
this.mBrushEraserSize = brushEraserSize;
setBrushDrawingMode(true);
}
void setBrushEraserColor(#ColorInt int color) {
mDrawPaint.setColor(color);
setBrushDrawingMode(true);
}
float getEraserSize() {
return mBrushEraserSize;
}
public float getBrushSize() {
return mBrushSize;
}
int getBrushColor() {
return mDrawPaint.getColor();
}
public void clearAll() {
mDrawnPaths.clear();
mRedoPaths.clear();
if (mDrawCanvas != null) {
mDrawCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
}
invalidate();
}
void setBrushViewChangeListener(BrushViewChangeListener brushViewChangeListener) {
mBrushViewChangeListener = brushViewChangeListener;
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
Bitmap canvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mDrawCanvas = new Canvas(canvasBitmap);
}
#Override
protected void onDraw(Canvas canvas) {
for (BrushLinePath linePath : mDrawnPaths) {
canvas.drawPath(linePath.getDrawPath(), linePath.getDrawPaint());
}
canvas.drawPath(mPath, mDrawPaint);
/////
final Bitmap scaledBitmap = getScaledBitmap();
final float centerX = scaledBitmap.getWidth() / 2;
final float centerY = scaledBitmap.getHeight() / 2;
final PathMeasure pathMeasure = new PathMeasure(mPath, false);
float distance = scaledBitmap.getWidth() / 2;
float[] position = new float[2];
float[] slope = new float[2];
float slopeDegree;
while (distance < pathMeasure.getLength())
{
pathMeasure.getPosTan(distance, position, slope);
slopeDegree = (float)((Math.atan2(slope[1], slope[0]) * 180f) / Math.PI);
canvas.save();
canvas.translate(position[0] - centerX, position[1] - centerY);
canvas.rotate(slopeDegree, centerX, centerY);
canvas.drawBitmap(scaledBitmap, 0, 0, mDrawPaint);
canvas.restore();
distance += scaledBitmap.getWidth() + 10;
}
}
/////
private Bitmap getScaledBitmap()
{
// width / height of the bitmap[
float width = brushBitmap.getWidth();
float height = brushBitmap.getHeight();
// ratio of the bitmap
float ratio = width / height;
// set the height of the bitmap to the width of the path (from the paint object).
float scaledHeight = mDrawPaint.getStrokeWidth();
// to maintain aspect ratio of the bitmap, use the height * ratio for the width.
float scaledWidth = scaledHeight * ratio;
// return the generated bitmap, scaled to the correct size.
return Bitmap.createScaledBitmap(brushBitmap, (int)scaledWidth, (int)scaledHeight, true);
}
/**
* Handle touch event to draw paint on canvas i.e brush drawing
*
* #param event points having touch info
* #return true if handling touch events
*/
#SuppressLint("ClickableViewAccessibility")
#Override
public boolean onTouchEvent(#NonNull MotionEvent event) {
if (mBrushDrawMode) {
float touchX = event.getX();
float touchY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touchStart(touchX, touchY);
break;
case MotionEvent.ACTION_MOVE:
touchMove(touchX, touchY);
break;
case MotionEvent.ACTION_UP:
touchUp();
break;
}
invalidate();
return true;
} else {
return false;
}
}
boolean undo() {
if (!mDrawnPaths.empty()) {
mRedoPaths.push(mDrawnPaths.pop());
invalidate();
}
if (mBrushViewChangeListener != null) {
mBrushViewChangeListener.onViewRemoved(this);
}
return !mDrawnPaths.empty();
}
boolean redo() {
if (!mRedoPaths.empty()) {
mDrawnPaths.push(mRedoPaths.pop());
invalidate();
}
if (mBrushViewChangeListener != null) {
mBrushViewChangeListener.onViewAdd(this);
}
return !mRedoPaths.empty();
}
private void touchStart(float x, float y) {
mRedoPaths.clear();
mPath.reset();
mPath.moveTo(x, y);
mTouchX = x;
mTouchY = y;
if (mBrushViewChangeListener != null) {
mBrushViewChangeListener.onStartDrawing();
}
}
private void touchMove(float x, float y) {
float dx = Math.abs(x - mTouchX);
float dy = Math.abs(y - mTouchY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(mTouchX, mTouchY, (x + mTouchX) / 2, (y + mTouchY) / 2);
mTouchX = x;
mTouchY = y;
}
}
private void touchUp() {
mPath.lineTo(mTouchX, mTouchY);
// Commit the path to our offscreen
mDrawCanvas.drawPath(mPath, mDrawPaint);
// kill this so we don't double draw
mDrawnPaths.push(new BrushLinePath(mPath, mDrawPaint));
/////
final Bitmap scaledBitmap = getScaledBitmap();
final float centerX = scaledBitmap.getWidth() / 2;
final float centerY = scaledBitmap.getHeight() / 2;
final PathMeasure pathMeasure = new PathMeasure(mPath, false);
float distance = scaledBitmap.getWidth() / 2;
float[] position = new float[2];
float[] slope = new float[2];
float slopeDegree;
while (distance < pathMeasure.getLength())
{
pathMeasure.getPosTan(distance, position, slope);
slopeDegree = (float)((Math.atan2(slope[1], slope[0]) * 180f) / Math.PI);
mDrawCanvas.save();
mDrawCanvas.translate(position[0] - centerX, position[1] - centerY);
mDrawCanvas.rotate(slopeDegree, centerX, centerY);
mDrawCanvas.drawBitmap(scaledBitmap, 0, 0, mDrawPaint);
mDrawCanvas.restore();
distance += scaledBitmap.getWidth() + 10;
}
/////
mPath = new Path();
if (mBrushViewChangeListener != null) {
mBrushViewChangeListener.onStopDrawing();
mBrushViewChangeListener.onViewAdd(this);
}
}
#VisibleForTesting
Paint getDrawingPaint() {
return mDrawPaint;
}
#VisibleForTesting
Pair<Stack<BrushLinePath>, Stack<BrushLinePath>> getDrawingPath() {
return new Pair<>(mDrawnPaths, mRedoPaths);
}
}
public interface BrushViewChangeListener {
void onViewAdd(BrushDrawingView brushDrawingView);
void onViewRemoved(BrushDrawingView brushDrawingView);
void onStartDrawing();
void onStopDrawing();
}
class BrushLinePath {
private final Paint mDrawPaint;
private final Path mDrawPath;
BrushLinePath(final Path drawPath, final Paint drawPaints) {
mDrawPaint = new Paint(drawPaints);
mDrawPath = new Path(drawPath);
}
Paint getDrawPaint() {
return mDrawPaint;
}
Path getDrawPath() {
return mDrawPath;
}
}
The reason it happens is because Paint doesn't have an alpha composing mode set by default. Thus, when you're trying to paint a bitmap over your canvas it will replace the destination pixels with your brush pixels, which in your case is #00000000. And that will result in pixel being displayed as black. Have a look into this documentation: https://developer.android.com/reference/android/graphics/PorterDuff.Mode
By the first glance it seems you're looking for PorterDuff.Mode.SRC_OVER or PorterDuff.Mode.SRC_ATOP - this way transparent pixels from your source image (your brush) will not over-draw the pixels from your destination (canvas). In case your background is always non-transparent, you will see no difference between SRC_OVER and SRC_ATOP, but if it isn't - choose the one which fits your needs. Then you can modify setupPathAndPaint method by adding this line to its end:
mDrawPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER));
I found this code on stack and it works well. However, there is an issue. While I'm able to set its background color, the color changes to black as soon as the clearSignature() function is called.
Why is that happening?
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/**
* A simple view to capture a path traced onto the screen. Initially intended to
* be used to captures signatures.
*
* #author Andrew Crichton
* #version 0.1
*/
public class SignatureView extends View
{
private Path mPath;
private Paint mPaint;
private Paint bgPaint = new Paint(Color.TRANSPARENT);
private Bitmap mBitmap;
private Canvas mCanvas;
private float curX, curY;
private static final int TOUCH_TOLERANCE = 4;
private static final int STROKE_WIDTH = 4;
boolean modified = false;
public SignatureView(Context context)
{
super(context);
init();
}
public SignatureView(Context context, AttributeSet attrs)
{
super(context, attrs);
init();
}
public SignatureView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
init();
}
private void init()
{
setFocusable(true);
mPath = new Path();
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setColor(Color.WHITE);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(STROKE_WIDTH);
}
public void setSigColor(int color)
{
mPaint.setColor(color);
}
public void setSigColor(int a, int red, int green, int blue)
{
mPaint.setARGB(a, red, green, blue);
}
public boolean clearSignature()
{
if (mBitmap != null)
createFakeMotionEvents();
if (mCanvas != null)
{
mCanvas.drawColor(Color.BLACK);
mCanvas.drawPaint(bgPaint);
mPath.reset();
invalidate();
}
else
{
return false;
}
return true;
}
public Bitmap getImage()
{
return this.mBitmap;
}
public void setImage(Bitmap bitmap)
{
this.mBitmap = bitmap;
this.invalidate();
}
public boolean hasChanged()
{
return modified;
}
#Override protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight)
{
int bitmapWidth = mBitmap != null ? mBitmap.getWidth() : 0;
int bitmapHeight = mBitmap != null ? mBitmap.getWidth() : 0;
if (bitmapWidth >= width && bitmapHeight >= height)
return;
if (bitmapWidth < width)
bitmapWidth = width;
if (bitmapHeight < height)
bitmapHeight = height;
Bitmap newBitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888);
Canvas newCanvas = new Canvas();
newCanvas.setBitmap(newBitmap);
if (mBitmap != null)
newCanvas.drawBitmap(mBitmap, 0, 0, null);
mBitmap = newBitmap;
mCanvas = newCanvas;
}
private void createFakeMotionEvents()
{
MotionEvent downEvent = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis() + 100, MotionEvent.ACTION_DOWN,
1f, 1f, 0);
MotionEvent upEvent = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis() + 100, MotionEvent.ACTION_UP, 1f,
1f, 0);
onTouchEvent(downEvent);
onTouchEvent(upEvent);
}
#Override protected void onDraw(Canvas canvas)
{
modified = true;
canvas.drawColor(Color.RED);
canvas.drawBitmap(mBitmap, 0, 0, mPaint);
canvas.drawPath(mPath, mPaint);
}
#Override public boolean onTouchEvent(MotionEvent event)
{
float x = event.getX();
float y = event.getY();
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
touchDown(x, y);
break;
case MotionEvent.ACTION_MOVE:
touchMove(x, y);
break;
case MotionEvent.ACTION_UP:
touchUp();
break;
}
invalidate();
return true;
}
/**
* ---------------------------------------------------------- Private
* methods ---------------------------------------------------------
*/
private void touchDown(float x, float y)
{
mPath.reset();
mPath.moveTo(x, y);
curX = x;
curY = y;
}
private void touchMove(float x, float y)
{
float dx = Math.abs(x - curX);
float dy = Math.abs(y - curY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE)
{
mPath.quadTo(curX, curY, (x + curX) / 2, (y + curY) / 2);
curX = x;
curY = y;
}
}
private void touchUp()
{
mPath.lineTo(curX, curY);
if (mCanvas == null)
{
mCanvas = new Canvas();
mCanvas.setBitmap(mBitmap);
}
mCanvas.drawPath(mPath, mPaint);
mPath.reset();
}
}
Well I have updated the original SignatureView code, now it supports a custom signature background color. This color is different from the view's background color!
setSigBackgroundColor()
I also made some other optimizations, use on your own risk as this is minimal tested!
Small list of optimizations:
Better bitmap recycling etc.
Recycling of MotionEvents
Added signature background color set method
Optimizations
Changed setImage method, although still not very safe to use!
New code:
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/**
* A simple view to capture a path traced onto the screen. Initially intended to
* be used to captures signatures.
*
* #author Andrew Crichton
* #version 0.1.1
*
* Modified by Rolf Smit
* -Recycle bitmaps
* -Recycle MotionEvents
* -Signature Background color changes
* -Optimizations
* -Changed setImage method, although still unsafe to use!
*/
public class SignatureView extends View {
private Path mPath;
private Paint mPaint;
private Bitmap mBitmap;
private Canvas mCanvas;
private int sigBackgroundColor = Color.TRANSPARENT;
private float curX, curY;
private static final int TOUCH_TOLERANCE = 4;
private static final int STROKE_WIDTH = 4;
boolean modified = false;
public SignatureView(Context context) {
super(context);
init();
}
public SignatureView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public SignatureView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
setFocusable(true);
mPath = new Path();
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setColor(Color.WHITE);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(STROKE_WIDTH);
}
public void setSigColor(int color) {
mPaint.setColor(color);
}
public void setSigColor(int alpha, int red, int green, int blue) {
mPaint.setARGB(alpha, red, green, blue);
}
public void setSigBackgroundColor(int color){
sigBackgroundColor = color;
}
public void setSigBackgroundColor(int alpha, int red, int green, int blue){
sigBackgroundColor = Color.argb(alpha, red, green, blue);
}
public boolean clearSignature() {
if (mBitmap != null) {
createFakeMotionEvents();
}
if (mCanvas != null) {
mCanvas.drawColor(sigBackgroundColor);
mPath.reset();
invalidate();
} else {
return false;
}
return true;
}
public Bitmap getImage() {
return Bitmap.createBitmap(mBitmap);
}
public void setImage(Bitmap bitmap){
this.mBitmap = bitmap;
if(mCanvas != null){
mCanvas.setBitmap(mBitmap);
}
}
public boolean hasChanged() {
return modified;
}
#Override
protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
int bitmapWidth = mBitmap != null ? mBitmap.getWidth() : 0;
int bitmapHeight = mBitmap != null ? mBitmap.getWidth() : 0;
if (bitmapWidth >= width && bitmapHeight >= height) {
return;
}
if (bitmapWidth < width) {
bitmapWidth = width;
}
if (bitmapHeight < height) {
bitmapHeight = height;
}
Bitmap newBitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888);
Canvas newCanvas = new Canvas();
newCanvas.setBitmap(newBitmap);
mCanvas = newCanvas;
if (mBitmap != null) {
newCanvas.drawBitmap(mBitmap, 0, 0, null);
mBitmap.recycle();
} else {
newCanvas.drawColor(sigBackgroundColor);
}
mBitmap = newBitmap;
}
private void createFakeMotionEvents() {
MotionEvent downEvent = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis() + 100, MotionEvent.ACTION_DOWN, 1f, 1f, 0);
MotionEvent upEvent = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis() + 100, MotionEvent.ACTION_UP, 1f, 1f, 0);
onTouchEvent(downEvent);
onTouchEvent(upEvent);
downEvent.recycle();
upEvent.recycle();
}
#Override
protected void onDraw(Canvas canvas) {
modified = true;
canvas.drawBitmap(mBitmap, 0, 0, mPaint);
canvas.drawPath(mPath, mPaint);
}
#SuppressLint("ClickableViewAccessibility")
#Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touchDown(x, y);
break;
case MotionEvent.ACTION_MOVE:
touchMove(x, y);
break;
case MotionEvent.ACTION_UP:
touchUp();
break;
}
invalidate();
return true;
}
private void touchDown(float x, float y) {
mPath.reset();
mPath.moveTo(x, y);
curX = x;
curY = y;
}
private void touchMove(float x, float y) {
float dx = Math.abs(x - curX);
float dy = Math.abs(y - curY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(curX, curY, (x + curX) / 2, (y + curY) / 2);
curX = x;
curY = y;
}
}
private void touchUp() {
mPath.lineTo(curX, curY);
if (mCanvas == null) {
mCanvas = new Canvas();
mCanvas.setBitmap(mBitmap);
}
mCanvas.drawPath(mPath, mPaint);
mPath.reset();
}
}
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;
};
I am using a custom view component to draw a pie ( a simple pie) . Each list Item has a pie with different values.
Now when I use it in a list view the pie values are shuffled and sometimes not updated.
My default pie value is 1.
When I first open my list
the first item shows proper value rest of the list items show only the defalt value 1 regardless of the actual value.
When I scroll the list the pie get value but that are shuffled . The first item has value of 5th , 2nd has value of 3rd and 3rd has value of something else.
Code of custom view:
public class PieRating extends View{
private float Rate;
private Paint p;
private int startX;
private int startY;
private int radius;
private ArrayList<Integer> colors;
private ArrayList<Float> values;
Bitmap bitmap;
Context mContext;
public PieRating(Context context, AttributeSet attrs) {
super(context, attrs);
Rate=1;
mContext = context;
p = new Paint();
p.setAntiAlias(true);
colors = new ArrayList<Integer>();
values = new ArrayList<Float>();
startX = 0;
startY = 0;
radius = 20;
colors.add(Color.GRAY);
colors.add(Color.TRANSPARENT);
values.add(Rate);
values.add(5 - Rate);
}
public void setRating(float Rate) {
this.Rate = Rate;
values.clear();
values.add(Rate);
values.add(5 - Rate);
}
public float getRating(){
return Rate;
}
#Override
protected void onDraw(Canvas canvas) {
float offset = 0;
float sum = 0;
for (int a = 0; a < values.size(); a++) {
sum += values.get(a);
}
float angle = (float) (360 / sum);
RectF rectF = new RectF();
rectF.set(getStartX(), getStartY(), getStartX() + getRadius(),
getStartY() + getRadius());
for (int i = 0; i < values.size(); i++) {
p.setColor(colors.get(i));
if (i == 0) {
canvas.drawArc(rectF, 270, values.get(i) * angle, true, p);
}
else {
canvas.drawArc(rectF, offset, values.get(i) * angle, true, p);
}
offset += (values.get(i) * angle + 270);
}
canvas.save();
}
public int getStartX() {
return startX;
}
public void setStartX(int startX) {
this.startX = startX;
}
public int getStartY() {
return startY;
}
public void setStartY(int startY) {
this.startY = startY;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
public ArrayList<Integer> getColors() {
return colors;
}
public void setColors(ArrayList<Integer> colors) {
this.colors = colors;
}
public ArrayList<Float> getValues() {
return values;
}
public void setValues(ArrayList<Float> values) {
this.values = values;
}
}
And my list
public View getView(int position, View convertView, ViewGroup parent) {
PieRating pr =((PieRating)findViewById(R.id.score_pie_container));
try
{
float rating = Float.parseFloat(JSONHelper.getString(mRestaurants, "restaurants.restaurant[].opinion.general", new int[] { position }));
pr.setRating(rating);
}
catch (Exception e) {
// TODO: handle exception
}
}
Tried calling pr.invalidate once I set rating but no good.
silly mistake
((PieRating)convertView.findViewById(R.id.score_pie_container))
I missed the convertView part ..
Leaving answer just in case someone runs into similar issue
Here is the custom class of GradientTextView provided by #koush (source is there on (github)
Now I got the class but how to call this class anyone can help since I am new bee on android
As far as I understood it can use custom attribute to but nyways how to call this class from MainActivity to get run. I dont know how to send AttributeSet parameters. it's too confusing
package android.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.LinearGradient;
import android.graphics.Shader.TileMode;
import android.text.BoringLayout;
import android.util.AttributeSet;
import android.widget.TextView;
public class GradientTextView extends TextView {
public GradientTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
int mStartColor = 0;
int mEndColor = 0;
float mAngle;
String mText;
BoringLayout mLayout;
public GradientTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
int[] ids = new int[attrs.getAttributeCount()];
for (int i = 0; i < attrs.getAttributeCount(); i++) {
ids[i] = attrs.getAttributeNameResource(i);
}
TypedArray a = context.obtainStyledAttributes(attrs, ids, defStyle, 0);
for (int i = 0; i < attrs.getAttributeCount(); i++) {
String attrName = attrs.getAttributeName(i);
if (attrName == null)
continue;
if (attrName.equals("startColor")) {
mStartColor = a.getColor(i, -1);
}
else if (attrName.equals("endColor")) {
mEndColor = a.getColor(i, -1);
}
else if (attrName.equals("angle")) {
mAngle = a.getFloat(i, 0);
}
}
}
public static void setGradient(TextView tv, float angle, int startColor, int endColor) {
tv.measure(tv.getLayoutParams().width, tv.getLayoutParams().height);
LinearGradient gradient = getGradient(tv.getMeasuredWidth(), tv.getMeasuredHeight(), angle, startColor, endColor);
tv.getPaint().setShader(gradient);
}
static LinearGradient getGradient(int measuredWidth, int measuredHeight, float angle, int startColor, int endColor) {
// calculate a vector for this angle
double rad = Math.toRadians(angle);
double oa = Math.tan(rad);
double x;
double y;
if (oa == Double.POSITIVE_INFINITY) {
y = 1;
x = 0;
}
else if (oa == Double.NEGATIVE_INFINITY) {
y = -1;
x = 0;
}
else {
y = oa;
if (rad > Math.PI)
x = -1;
else
x = 1;
}
// using the vector, calculate the start and end points from the center of the box
int mx = measuredWidth;
int my = measuredHeight;
int cx = mx / 2;
int cy = my / 2;
double n;
if (x == 0) {
n = (double)cy / y;
}
else if (y == 0) {
n = (double)cx / x;
}
else {
n = (double)cy / y;
double n2 = (double)cx / x;
if (Math.abs(n2) < Math.abs(n))
n = n2;
}
int sx = (int)(cx - n * x);
int sy = (int)(cy - n * y);
int ex = (int)(cx + n * x);
int ey = (int)(cy + n * y);
return new LinearGradient(sx, sy, ex, ey, startColor, endColor, TileMode.CLAMP);
}
protected void onDraw(android.graphics.Canvas canvas) {
if (mGradient == null) {
mGradient = getGradient(getMeasuredWidth(), getMeasuredHeight(), mAngle, mStartColor, mEndColor);
getPaint().setShader(mGradient);
}
super.onDraw(canvas);
}
public int getStartColor() {
return mStartColor;
}
public void setStartColor(int startColor) {
mStartColor = startColor;
invalidate();
}
public int getEndColor() {
return mEndColor;
}
public void setEndColor(int endColor) {
mEndColor = endColor;
invalidate();
}
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
mGradient = null;
}
LinearGradient mGradient;
}
This custom class are too confusing but they are used for tweaking like outline, gradients, and etc I am very keen to understand the flow
you can use this "View Element" by instanciating/using a view object:
TextView myView = new TextView (this);
myView.setText("Test");
GradientTextView.setGradient(myView, 90, Color.BLACK, Color.WHITE);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
Layoutparams.WRAP_CONTENT);
myLayout.addView(myView, params);
You can even use this object using it your layouts XML file.