Related
I've written a custom view that generate a Google Map Marker at runtime, code below:
public class CustomMapMarker extends View {
Paint paint;
Path bodyPath;
Path dotPath;
private Paint paint2;
private int backGroundColor;
private int foreGroundColor;
Matrix scaleMatrix;
public CustomMapMarker(Context context)
{
super(context);
init(context);
}
public CustomMapMarker(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomMapMarker);
try {
backGroundColor = a.getColor(R.styleable.CustomMapMarker_markerBackgroundColor, Color.parseColor("#4180e0"));
foreGroundColor = a.getColor(R.styleable.CustomMapMarker_dotBackgroundColor, Color.WHITE);
}
finally {
a.recycle();
}
init(context);
}
public CustomMapMarker(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
scaleMatrix = new Matrix();
bodyPath = new Path();
dotPath = new Path();
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.FILL);
paint.setColor(backGroundColor);
paint2 = new Paint(Paint.ANTI_ALIAS_FLAG);
paint2.setStyle(Paint.Style.FILL);
paint2.setColor(foreGroundColor);
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public void onDraw(Canvas canvas)
{
bodyPath.setFillType(Path.FillType.EVEN_ODD);
bodyPath.moveTo(132, 416);
bodyPath.cubicTo(123, 370, 107, 332, 87, 297);
bodyPath.cubicTo(72, 270, 55, 246, 39, 221);
bodyPath.cubicTo(33, 212, 29, 203, 24, 194);
bodyPath.cubicTo(14,177,5,156, 6, 130);
bodyPath.cubicTo(6,104,14,83,25,66);
bodyPath.cubicTo(42,38,72,15,112,9);
bodyPath.cubicTo(145, 4, 176,12,197,25);
bodyPath.cubicTo(215, 36, 229,49,239,66);
bodyPath.cubicTo(250, 83, 258, 103,258,129);
bodyPath.cubicTo(259, 143, 256, 155, 253, 166);
bodyPath.cubicTo(250, 176, 245, 185, 241, 194);
bodyPath.cubicTo(232, 212, 221, 229, 210, 246);
bodyPath.cubicTo(177, 296, 146, 347, 132, 416);
bodyPath.close();
dotPath.setFillType(Path.FillType.EVEN_ODD);
dotPath.arcTo(82, 85, 182, 185, 270, 360, true);
dotPath.close();
bodyPath.addPath(dotPath);
RectF drawableRect = new RectF(0, 0, 265, 412);
RectF viewRect = new RectF(0, 0, getWidth(), getHeight());
scaleMatrix.setRectToRect(drawableRect, viewRect, Matrix.ScaleToFit.CENTER);
bodyPath.transform(scaleMatrix);
dotPath.transform(scaleMatrix);
canvas.drawPath(bodyPath, paint);
canvas.drawPath(dotPath, paint2);
}
public void setBackgroundColor(int mColor) {
this.backGroundColor = mColor;
this.invalidate();
}
public void setForeGroundColor(int mColor) {
this.foreGroundColor = mColor;
this.invalidate();
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int desiredWidth = 255;
int desiredHeight = 412;
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int width;
int height;
if (widthMode == MeasureSpec.EXACTLY) {
width = widthSize;
} else if (widthMode == MeasureSpec.AT_MOST) {
width = Math.min(desiredWidth, widthSize);
} else {
width = desiredWidth;
}
if (heightMode == MeasureSpec.EXACTLY) {
height = heightSize;
} else if (heightMode == MeasureSpec.AT_MOST) {
height = Math.min(desiredHeight, heightSize);
} else {
height = desiredHeight;
}
setMeasuredDimension(width, height);
}
}
Which in the XML preview, displays as intended:
However, at runtime, embedding this marker somewhere in the app to test with, the white dot is not visible?
Would anyone with more experience with custom views be able to shed some light on this? I presume it's something to do with the way i'm scaling the path to make it fit any size?
I finally found some time to look at your problem.
1) Use addArc() instead of arcTo(). If all you want is a circle, don't use a path, use canvas.drawCircle(). I'd do that.
2) Do not create objects in onDraw(). Use onSizeChanged() to create your pathes, that's the time when you know how big your view is. You can then calculate your path depending on width and height of your view. Thus you don't need to scale anything. In onDraw() you just draw.
#Override
public void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
bodyPath = getBodyPath(width, height);
dotPath = getDotPath(width, height);
}
#Override
public void onDraw(Canvas canvas)
{
canvas.save();
if(bodyPath != null) {
canvas.drawPath(bodyPath, backgroundPaint);
}
if(dotPath != null) {
canvas.drawPath(dotPath, foregroundPaint);
}
//or just a circle
//canvas.drawCircle(getWidth()/2, getHeight()/3,Math.min(getWidth(),getHeight())/5,foregroundPaint);
canvas.restore();
}
getBodyPath() e.g. looks like this
private Path getOutlinePath(float w, float h) {
Path bodyPath = new Path();
bodyPath.setFillType(Path.FillType.EVEN_ODD);
bodyPath.moveTo(w* 0.5f, h);
bodyPath.cubicTo(w * 0.4f, h * 0.8f, w * 0.3f, h * 0.7f, w * 0.25f, h * 0.6f);
bodyPath.cubicTo(w * 0.2f, h * 0.5f, w * 0.1f, h * 0.5f, 0, h * 0.3f);
bodyPath.cubicTo(0, h * 0.25f, w * 0.25f, 0, w * 0.5f, 0);
bodyPath.cubicTo(w * 0.75f, 0, w, h * 0.25f, w, h * 0.5f);
bodyPath.close();
return bodyPath;
}
Yes it is an ugly path, but you can see how I use the width and height of the view to calculate the control points. That way you don't need your scale matrix and you don't need onMeasure(). The path will fit any size.
I need to make something like this:
I'd try to draw this using Canvas.drawArc(...) but I failed.
Can anyone help me?
I created a view that can draw the shape that you want.
It starts by creating a path for one of the quarters, and rotating the canvas by 90 degrees to draw the path 4 times. The Paint used to draw the Path is determined by the progress / maxProgress.
I used a second path to denote the region of the canvas to clip out when drawing, so that there are empty spaces between the quarters.
Finally, the text can be drawn in the middle after restoring the canvas rotation and clipping.
public class CustomProgressView extends View {
private int progress;
private int maxProgress;
private float arcWidth;
private float arcPadding;
private Paint paintPositive;
private Paint paintNegative;
private Paint paintText;
private Path path;
private Path clipPath;
private ProgressListener listener;
public CustomProgressView(Context context) {
super(context);
init();
}
public CustomProgressView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomProgressView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
arcWidth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 25, getResources().getDisplayMetrics());
arcPadding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 6, getResources().getDisplayMetrics());
paintPositive = new Paint();
paintPositive.setColor(Color.RED);
paintPositive.setStyle(Paint.Style.FILL_AND_STROKE);
paintPositive.setAntiAlias(true);
paintNegative = new Paint();
paintNegative.setColor(Color.BLUE);
paintPositive.setStyle(Paint.Style.FILL_AND_STROKE);
paintNegative.setAntiAlias(true);
paintText = new Paint();
paintText.setColor(Color.BLACK);
paintText.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 24, getResources().getDisplayMetrics()));
progress = 0;
maxProgress = 10;
}
#Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
float diameter = Math.min(getWidth(), getHeight());
RectF ovalOuter = new RectF(0, 0, diameter, diameter);
RectF ovalInner = new RectF(ovalOuter.left + arcWidth, ovalOuter.top + arcWidth, ovalOuter.right - arcWidth, ovalOuter.bottom - arcWidth);
path = new Path();
path.moveTo(ovalOuter.centerX(), ovalOuter.top);
path.addArc(ovalOuter, 270, 90);
path.lineTo(ovalInner.right, ovalInner.centerY());
path.addArc(ovalInner, 0, -90);
path.lineTo(ovalOuter.centerX(), ovalOuter.top);
clipPath = new Path();
clipPath.addRect(ovalOuter.left, ovalOuter.centerY() - arcPadding / 2, ovalOuter.right, ovalOuter.centerY() + arcPadding / 2, Path.Direction.CW);
clipPath.addRect(ovalOuter.centerX() - arcPadding / 2, ovalOuter.top, ovalOuter.centerX() + arcPadding / 2, ovalOuter.bottom, Path.Direction.CW);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float perc = (float) progress / (float) maxProgress;
int state = 0;
if (perc < 0.25) {
state = 1;
} else if (perc < 0.5) {
state = 2;
} else if (perc < 0.75) {
state = 3;
} else {
state = 4;
}
RectF bounds = new RectF();
path.computeBounds(bounds, true);
// Draw Circle
canvas.save();
// Clip padding
canvas.clipPath(clipPath, Region.Op.DIFFERENCE);
canvas.drawPath(path, state == 1 ? paintPositive : paintNegative);
canvas.rotate(90, bounds.left, bounds.bottom);
canvas.drawPath(path, state == 2 ? paintPositive : paintNegative);
canvas.rotate(90, bounds.left, bounds.bottom);
canvas.drawPath(path, state == 3 ? paintPositive : paintNegative);
canvas.rotate(90, bounds.left, bounds.bottom);
canvas.drawPath(path, state == 4 ? paintPositive : paintNegative);
canvas.restore();
// Draw Progress
String text = String.valueOf(progress);
Rect textBounds = new Rect();
paintText.getTextBounds(text, 0, text.length(), textBounds);
float x = bounds.left - textBounds.width() / 2;
float y = bounds.bottom + textBounds.height() / 2;
canvas.drawText(text, x, y, paintText);
}
public int getProgress() {
return progress;
}
public void setProgress(int progress) {
int oldProgress = this.progress;
this.progress = progress;
if (listener != null) {
listener.onProgressChanged(oldProgress, progress);
}
invalidate();
}
public int getMaxProgress() {
return maxProgress;
}
public void setMaxProgress(int maxProgress) {
this.maxProgress = maxProgress;
invalidate();
}
public ProgressListener getListener() {
return listener;
}
public void setListener(ProgressListener listener) {
this.listener = listener;
}
public interface ProgressListener {
void onProgressChanged(int oldProgress, int newProgress);
}
}
I tried to replicate a donut chart code that I found in the net. The code is as follows
public class DonutChart extends View{
private float radius;
SharedPreferences prefs;
Paint paint;
Paint shadowPaint;
int a,b,c;
Path myPath;
Path shadowPath;
RectF outterCircle;
RectF innerCircle;
RectF shadowRectF;
public DonutChart(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.DonutChart,
0, 0
);
try {
radius = a.getDimension(R.styleable.DonutChart_radius, 20.0f);
} finally {
a.recycle();
}
paint = new Paint();
paint.setDither(true);
paint.setStyle(Paint.Style.FILL);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setAntiAlias(true);
paint.setStrokeWidth(radius / 14.0f);
shadowPaint = new Paint();
shadowPaint.setColor(0xf0000000);
shadowPaint.setStyle(Paint.Style.STROKE);
shadowPaint.setAntiAlias(true);
shadowPaint.setStrokeWidth(6.0f);
shadowPaint.setMaskFilter(new BlurMaskFilter(4, BlurMaskFilter.Blur.SOLID));
myPath = new Path();
shadowPath = new Path();
outterCircle = new RectF();
innerCircle = new RectF();
shadowRectF = new RectF();
float adjust = (.019f*radius);
shadowRectF.set(adjust, adjust, radius*2-adjust, radius*2-adjust);
adjust = .038f * radius;
outterCircle.set(adjust, adjust, radius*2-adjust, radius*2-adjust);
adjust = .276f * radius;
innerCircle.set(adjust, adjust, radius * 2 - adjust, radius * 2 - adjust);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// draw shadow
paint.setShader(null);
float adjust = (.0095f*radius);
paint.setShadowLayer(8, adjust, -adjust, 0xaa000000);
drawDonut(canvas, paint, 0, 359.9f);
//Orange
setGradient(0xffEF6632,0xffEF6632);
drawDonut(canvas,paint, 0,b);
//Blue
setGradient(0xff00CCDA,0xff00CCDA);
drawDonut(canvas, paint, 60,a);
// blue
// setGradient(0xff4AB6C1,0xff2182AD);
// drawDonut(canvas, paint, 120, 60);
// Grey
setGradient(0xff557687,0xff557687);
drawDonut(canvas, paint, 180,c);
}
public void drawDonut(Canvas canvas, Paint paint, float start,float sweep){
myPath.reset();
myPath.arcTo(outterCircle, start, sweep, false);
myPath.arcTo(innerCircle, start+sweep, -sweep, false);
myPath.close();
canvas.drawPath(myPath, paint);
}
public void setGradient(int sColor, int eColor){
paint.setShader(new RadialGradient(radius, radius, radius - 5,
new int[]{sColor, eColor},
new float[]{.6f, .95f}, TileMode.CLAMP));
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int desiredWidth = (int) radius*2;
int desiredHeight = (int) radius*2;
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int width;
int height;
//70dp exact
if (widthMode == MeasureSpec.EXACTLY) {
width = widthSize;
}else if (widthMode == MeasureSpec.AT_MOST) {
//wrap content
width = Math.min(desiredWidth, widthSize);
} else {
width = desiredWidth;
}
//Measure Height
if (heightMode == MeasureSpec.EXACTLY) {
height = heightSize;
} else if (heightMode == MeasureSpec.AT_MOST) {
height = Math.min(desiredHeight, heightSize);
} else {
height = desiredHeight;
}
//MUST CALL THIS
setMeasuredDimension(width, height);
}
public void getData(int x,int y){
invalidate();
a=((x*360)/10);
b=(y*360)/10;
c=((10-(x+y))*360)/10;
String s1,s2,s3;
s1=String.valueOf(a);
s2=String.valueOf(b);
s3=String.valueOf(c);
Toast.makeText(getContext(),"Inside Chart "+s1+" "+s2+" "+s3 +" "+String.valueOf(x),Toast.LENGTH_SHORT).show();
}
}
The problem is when I render the graph on my device it gives me a weird shadow like this:
or like this:
What is causing this and how to rectify it?
This is actually caused because only the value of the line length is changed whereas the starting point is the same so sometimes they tend to overlap.
This can be solved by changing the code as follows
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// draw shadow
paint.setShader(null);
float adjust = (.0095f*radius);
paint.setShadowLayer(8, adjust, -adjust, 0xaa000000);
drawDonut(canvas, paint, 0, 359.9f);
//Orange
setGradient(0xffEF6632,0xffEF6632);
drawDonut(canvas,paint, 0,b);
//Blue
setGradient(0xff00CCDA,0xff00CCDA);
drawDonut(canvas, paint, b,a);
// Grey
setGradient(0xff557687,0xff557687);
drawDonut(canvas, paint, a+b,c);
}
I have IndicationBar class that should draw rectangle with logo inside and on int value case change rectangle color. I am new to java and android so im learning everyday.
At this moment the value of int is changing in other class and i call it BluetoothChat.statusSviesos. its public static int. Do i need to create interface Listener or how can i run private void Sviesos() every time int is changed? It runs only once in start.
public class IndicationBar extends View {
private static final String TAG = IndicationBar.class.getSimpleName();
// drawing tools
private RectF Rect;
private Paint rectPaint;
private Paint rimCirclePaint;
private RectF faceRect;
private Bitmap faceTexture;
private Paint facePaint;
private Paint rimShadowPaint;
private Paint titlePaint;
private Path titlePath;
private Paint logoPaint;
private Bitmap logo;
private Matrix logoMatrix;
private float logoScale;
private Paint backgroundPaint;
// end drawing tools
private Bitmap background; // holds the cached static part
public IndicationBar(Context context) {
super(context);
init();
}
public IndicationBar(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public IndicationBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
#Override
protected void onRestoreInstanceState(Parcelable state) {
Bundle bundle = (Bundle) state;
Parcelable superState = bundle.getParcelable("superState");
super.onRestoreInstanceState(superState);
}
private void init() {
initDrawingTools();
}
// private String getTitle() {
// return "DANCER";
// }
private void Sviesos(){
//Rect = new RectF(0.1f, 0.1f, 0.9f, 0.9f);
//rectPaint = new Paint();
//valueSviesos = BluetoothChat.statusSviesos;
switch(BluetoothChat.statusSviesos){
case 0 : rectPaint.setColor(Color.parseColor("#1BA1E2"));
break;
case 1 : rectPaint.setColor(Color.parseColor("#A05000"));
break;
case 2 : rectPaint.setColor(Color.parseColor("#E671B8"));
break;
case 3 : rectPaint.setColor(Color.parseColor("#F09609"));
break;
case 4 : rectPaint.setColor(Color.parseColor("#1BA1E2"));
break;
}
//rectPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
}
private void initDrawingTools() {
Rect = new RectF(0.1f, 0.1f, 0.9f, 0.9f);
rectPaint = new Paint();
rectPaint.setColor(Color.parseColor("#8CBF26"));
rectPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
Sviesos();
rimCirclePaint = new Paint();
rimCirclePaint.setAntiAlias(true);
rimCirclePaint.setStyle(Paint.Style.STROKE);
rimCirclePaint.setColor(Color.argb(0x4f, 0x33, 0x36, 0x33));
rimCirclePaint.setStrokeWidth(0.005f);
float rimSize = 0.02f;
faceRect = new RectF();
faceRect.set(Rect.left + rimSize, Rect.top + rimSize,
Rect.right - rimSize, Rect.bottom - rimSize);
faceTexture = BitmapFactory.decodeResource(getContext().getResources(),
R.drawable.plastic);
BitmapShader paperShader = new BitmapShader(faceTexture,
Shader.TileMode.MIRROR,
Shader.TileMode.MIRROR);
Matrix paperMatrix = new Matrix();
facePaint = new Paint();
facePaint.setFilterBitmap(true);
paperMatrix.setScale(1.0f / faceTexture.getWidth(),
1.0f / faceTexture.getHeight());
paperShader.setLocalMatrix(paperMatrix);
facePaint.setStyle(Paint.Style.FILL);
facePaint.setShader(paperShader);
rimShadowPaint = new Paint();
rimShadowPaint.setShader(new RadialGradient(0.5f, 0.5f, faceRect.width() / 2.0f,
new int[] { 0x00000000, 0x00000500, 0x50000500 },
new float[] { 0.96f, 0.96f, 0.99f },
Shader.TileMode.MIRROR));
rimShadowPaint.setStyle(Paint.Style.FILL);
titlePaint = new Paint();
titlePaint.setColor(Color.parseColor("#1BA1E2"));
titlePaint.setAntiAlias(true);
titlePaint.setTypeface(Typeface.DEFAULT_BOLD);
titlePaint.setTextAlign(Paint.Align.CENTER);
titlePaint.setTextSize(0.09f);
titlePaint.setTextScaleX(0.9f);
titlePath = new Path();
titlePath.addArc(new RectF(0.24f, 0.24f, 0.76f, 0.76f), -180.0f, -180.0f);
logoPaint = new Paint();
logoPaint.setFilterBitmap(true);
logo = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.sviesos);
logoMatrix = new Matrix();
logoScale = (1.0f / logo.getWidth()) * 0.3f;;
logoMatrix.setScale(logoScale, logoScale);
backgroundPaint = new Paint();
backgroundPaint.setFilterBitmap(true);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Log.d(TAG, "Width spec: " + MeasureSpec.toString(widthMeasureSpec));
Log.d(TAG, "Height spec: " + MeasureSpec.toString(heightMeasureSpec));
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int chosenWidth = chooseDimension(widthMode, widthSize);
int chosenHeight = chooseDimension(heightMode, heightSize);
int chosenDimension = Math.min(chosenWidth, chosenHeight);
setMeasuredDimension(chosenDimension, chosenDimension);
}
private int chooseDimension(int mode, int size) {
if (mode == MeasureSpec.AT_MOST || mode == MeasureSpec.EXACTLY) {
return size;
} else { // (mode == MeasureSpec.UNSPECIFIED)
return getPreferredSize();
}
}
// in case there is no size specified
private int getPreferredSize() {
return 300;
}
private void drawRect(Canvas canvas) {
// first, draw the metallic body
canvas.drawRect(Rect, rectPaint);
// now the outer rim circle
//canvas.drawOval(rimRect, rimCirclePaint);
}
// private void drawFace(Canvas canvas) {
// canvas.drawOval(faceRect, facePaint);
// // draw the inner rim circle
// canvas.drawOval(faceRect, rimCirclePaint);
// // draw the rim shadow inside the face
// canvas.drawOval(faceRect, rimShadowPaint);
// }
private void drawBackground(Canvas canvas) {
if (background == null) {
Log.w(TAG, "Background not created");
} else {
canvas.drawBitmap(background, 0, 0, backgroundPaint);
}
}
#Override
protected void onDraw(Canvas canvas) {
drawBackground(canvas);
float scale = (float) getWidth();
canvas.save(Canvas.MATRIX_SAVE_FLAG);
canvas.scale(scale, scale);
drawLogo(canvas);
canvas.restore();
}
private void drawLogo(Canvas canvas) {
canvas.save(Canvas.MATRIX_SAVE_FLAG);
canvas.translate(0.5f - logo.getWidth() * logoScale / 2.0f,
0.5f - logo.getHeight() * logoScale / 2.0f);
canvas.drawBitmap(logo, logoMatrix, logoPaint);
canvas.restore();
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
Log.d(TAG, "Size changed to " + w + "x" + h);
regenerateBackground();
}
private void regenerateBackground() {
// free the old bitmap
Sviesos();
if (background != null) {
background.recycle();
}
background = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
Canvas backgroundCanvas = new Canvas(background);
float scale = (float) getWidth();
backgroundCanvas.scale(scale, scale);
drawRect(backgroundCanvas);
}
}
Use the Observer pattern for this. Change the BluetoothChat
public class BluetoothChat {
private static int statusSviesos;
//the list of observers
private static List<Observer> observerList;
//adds an observer to observe statusSciesos
public static void addStatusSviesosObserver(Observer observer) {
observerList.add(observer);
}
//getter function returns the value
public static int getStatusSviesos(){
return statusSviesos;
}
//setter function sets the value and notifies observer
public static void setStatusSviesos(int statusSviesos){
BluetoothChat.statusSviesos=statusSviesos;
for(Observer current: observerList){
current.notifyChange(statusSviesos);
}
}
public static interface Observer {
public void notifyChange(int newStatus);
}
...
Then create an Observer in the IndicationBar and add it to the BluetoothChat:
Observer observer = new Observer() {
#Override
public void notifyChange(int newStatus) {
Sviesos();
}
};
BluetoothChat.addStatusSviesosObserver(observer);
This is a raw implementation of the Observer pattern. There should be a removeObserver-method too and it is not thread-safe. There is a default implementations ready in Java (Observer-class and Observable-class) and there are alternative implementations like PropertyChangeObserver. But for your current use case this should do the job. Also read Wikipedia and Vogellas tutorial
General tips:
Does BluetoothChat's attribute really has to be static? I recommend you to use static as less as possible. Better create an Object once and pass it around instead. You can search for "global state" and why to avoid it for further information.
You could create an array of Colors (or Color-strings like "#F09609") and access it with the int you get to get rid of the switch-statement.
Try to apply code style conventions everywhere, method names and variables should always start with a small letter (except constants which are ALL_BIG) and should be descriptive.
I'm trying to mimic something from the iPhone version of my app. I have a square image and I want to show it in a circle with a white border around it. like this
Is there a way I can do this?
You can achieve this effect, or something very close to it, using a custom Drawable class, containing a Paint object with a BitmapShader that renders the image as a texture. This is the code I'm using (slightly adapted from Romain's Guy post, which uses the same technique to draw images with rounded corners).
class CircularDrawable extends Drawable
{
private float mCircleRadius;
private final RectF mBackgroundRect = new RectF();
private final Paint mBackgroundPaint;
private final BitmapShader mBitmapShader;
private final Paint mPaint;
private final int mMargin;
CircularDrawable(Bitmap bitmap, int margin, int backgroundColor)
{
mBitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setShader(mBitmapShader);
mMargin = margin;
mBackgroundPaint = new Paint();
mBackgroundPaint.setColor(backgroundColor);
}
#Override
protected void onBoundsChange(Rect bounds)
{
super.onBoundsChange(bounds);
mBackgroundRect.set(bounds);
mCircleRadius = Math.min(bounds.width() / 2 - mMargin, bounds.height() / 2 - mMargin);
}
#Override
public void draw(Canvas canvas)
{
canvas.drawRect(mBackgroundRect, mBackgroundPaint);
canvas.drawCircle(mBackgroundRect.width() / 2, mBackgroundRect.height() / 2, mCircleRadius, mPaint);
}
#Override
public int getOpacity()
{
return PixelFormat.TRANSLUCENT;
}
#Override
public void setAlpha(int alpha)
{
mPaint.setAlpha(alpha);
mBackgroundPaint.setAlpha(alpha);
}
#Override
public void setColorFilter(ColorFilter cf)
{
mPaint.setColorFilter(cf);
mBackgroundPaint.setColorFilter(cf);
}
}
Having the bitmap you want to draw, just build a CircularDrawable from it with
new CircularDrawable(bitmap, margin, Color.WHITE);
Try this.
public class CircularImageView extends ImageView {
private int borderWidth;
private int viewWidth;
private int viewHeight;
private Bitmap image;
private Paint paint;
private Paint paintBorder;
private BitmapShader shader;
public CircularImageView(final Context context) {
this(context, null);
}
public CircularImageView(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.circularImageViewStyle);
}
public CircularImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// init paint
paint = new Paint();
paint.setAntiAlias(true);
paintBorder = new Paint();
paintBorder.setAntiAlias(true);
// load the styled attributes and set their properties
TypedArray attributes = context.obtainStyledAttributes(attrs,
R.styleable.CircularImageView, defStyle, 0);
if (attributes.getBoolean(R.styleable.CircularImageView_border, true)) {
setBorderWidth(attributes.getColor(
R.styleable.CircularImageView_border_width, 4));
setBorderColor(attributes.getInt(
R.styleable.CircularImageView_border_color, Color.WHITE));
}
if (attributes.getBoolean(R.styleable.CircularImageView_shadow, false))
addShadow();
}
public void setBorderWidth(int borderWidth) {
this.borderWidth = borderWidth;
this.invalidate();
}
public void setBorderColor(int borderColor) {
if (paintBorder != null)
paintBorder.setColor(borderColor);
this.invalidate();
}
public void addShadow() {
setLayerType(LAYER_TYPE_SOFTWARE, paintBorder);
paintBorder.setShadowLayer(4.0f, 0.0f, 2.0f, Color.BLACK);
}
#SuppressLint("DrawAllocation")
#Override
public void onDraw(Canvas canvas) {
// load the bitmap
BitmapDrawable bitmapDrawable = (BitmapDrawable) this.getDrawable();
if (bitmapDrawable != null)
image = bitmapDrawable.getBitmap();
// init shader
if (image != null) {
shader = new BitmapShader(Bitmap.createScaledBitmap(image,
canvas.getWidth(), canvas.getHeight(), false),
Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
paint.setShader(shader);
int circleCenter = viewWidth / 2;
// circleCenter is the x or y of the view's center
// radius is the radius in pixels of the cirle to be drawn
// paint contains the shader that will texture the shape
canvas.drawCircle(circleCenter + borderWidth, circleCenter
+ borderWidth, circleCenter + borderWidth - 4.0f,
paintBorder);
canvas.drawCircle(circleCenter + borderWidth, circleCenter
+ borderWidth, circleCenter - 4.0f, paint);
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = measureWidth(widthMeasureSpec);
int height = measureHeight(heightMeasureSpec, widthMeasureSpec);
viewWidth = width - (borderWidth * 2);
viewHeight = height - (borderWidth * 2);
setMeasuredDimension(width, height);
}
private int measureWidth(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
// We were told how big to be
result = specSize;
} else {
// Measure the text
result = viewWidth;
}
return result;
}
private int measureHeight(int measureSpecHeight, int measureSpecWidth) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpecHeight);
int specSize = MeasureSpec.getSize(measureSpecHeight);
if (specMode == MeasureSpec.EXACTLY) {
// We were told how big to be
result = specSize;
} else {
// Measure the text (beware: ascent is a negative number)
result = viewHeight;
}
return (result + 2);
}
}
I'd make a custom view and just draw what you want to the canvas- draw the border, then the white circle, then the image.It's a couple of easy canvas calls. If you need to clip the image to a circular area, just set a clipping Region before doing the image draw.