Android - Multiple colors & size in drawable shape style

为君一笑 提交于 2019-12-05 22:39:36

create a custom Drawable, this way you can have milions combinations of size/color:

class CircleDrawable extends Drawable {
...
}

So I followed the advice from pskink and created a CircleDrawable class.

It works quite nicely for my application (although I don't know if it's the right way...), so I thought I'd share it.

public CircleDrawable(Bitmap bitmap, Context context) {
    paint = new Paint();
    paint.setAntiAlias(true);
    paint.setStyle(Paint.Style.FILL);
    CircleDrawable.context = context;
    drawable = new ShapeDrawable(new OvalShape());
    setColor();  // supports multiple color
    setSize();  //supports multiple size
}

private void setColor() {

     // some algorithm to pick the right color...
    if (...)
        int color = context.getResources().getColor(R.color.pale_blue);

    paint.setColor(color);
}

    /* 
     * algorithm to set size here...
     */

@Override
public void draw(Canvas canvas) {

    //draw circle in the middle of the TextView 
    canvas.drawCircle(textViewSize, textViewSize, circleSize, paint);
}

And in the main code where I need to dynamically draw the circles:

    final float scale = getApplicationContext().getResources().getDisplayMetrics().density;
    int pixels = (int) (107.0f * scale + 0.5f);
    skills.setWidth(pixels);
    skills.setHeight(pixels);
    skills.setBackground(new CircleDrawable(null, getApplicationContext()));

And I ended up with a bunch of circles with different shapes and colors.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!