Advertisement
Guest User

Untitled

a guest
Feb 21st, 2019
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. public class DonutView extends View {
  2.  
  3. Context context;
  4. int value = 0;
  5. int size;
  6. int strokeSize;
  7. int textSize;
  8.  
  9. int width;
  10. int height;
  11.  
  12.  
  13. public DonutView(Context context) {
  14. super(context);
  15. this.context = context;
  16. init();
  17. }
  18.  
  19. public DonutView(Context context, AttributeSet attrs) {
  20. super(context, attrs);
  21. this.context = context;
  22. init();
  23. }
  24.  
  25. public DonutView(Context context, AttributeSet attrs, int defStyleAttr) {
  26. super(context, attrs, defStyleAttr);
  27. this.context = context;
  28. init();
  29. }
  30.  
  31. private void init() {
  32. size = getResources().getDimensionPixelSize(R.dimen.donut_size);
  33. strokeSize = getResources().getDimensionPixelSize(R.dimen.donut_stroke_size);
  34. textSize = getResources().getDimensionPixelSize(R.dimen.donut_text_size);
  35. }
  36.  
  37. @Override
  38. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  39. super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  40. width = MeasureSpec.getSize(widthMeasureSpec);
  41. height = MeasureSpec.getSize(heightMeasureSpec);
  42. }
  43.  
  44. public void setValue(int value) {
  45. this.value = value;
  46. invalidate();
  47. }
  48.  
  49. @Override
  50. protected void onDraw(Canvas canvas) {
  51. canvas.drawColor(Color.alpha(Color.CYAN)); // clear all
  52.  
  53. RectF rectF = new RectF(20, 20, size - 20, size - 20);
  54.  
  55. Paint paint = new Paint();
  56. paint.setColor(Color.LTGRAY);
  57. paint.setAntiAlias(true);
  58. paint.setStyle(Paint.Style.STROKE);
  59. paint.setStrokeWidth(strokeSize);
  60.  
  61. canvas.drawArc(rectF, 0, 360, false, paint);
  62.  
  63. paint.setColor(Color.RED);
  64. paint.setStrokeJoin(Paint.Join.ROUND);
  65. canvas.drawArc(rectF, -90, value, false, paint);
  66.  
  67. paint.setTextSize(textSize);
  68. paint.setStrokeWidth(5);
  69. paint.setColor(Color.RED);
  70. String txt = String.valueOf(value);
  71. int xPos = width / 2 - (int)(paint.measureText(txt) / 2);
  72. int yPos = (int)(height / 2 - ((paint.descent() + paint.ascent()) / 2));
  73. canvas.drawText(txt, xPos, yPos, paint);
  74. }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement