I have a drawable that will change colors sometimes, but it must ALWAYS have rounded corners. It's for a UI library, so I can't know what colors will it have. XML is not an option, I have to achieve this with pure java.
Is there a way to achieve this programatically WITHOUT using XML?
Create a custom Drawable (i.e. extend Drawable) and in its onDraw use Canvas.drawRoundRect(RectF rect, float rx, float ry, Paint paint), setting the Paint to the desired colour.
If you draw the drawable by yourself, you could set a clip path with Canvas.clipPath. The path would consist of one or more rectangles and some circles, which clip the rounded corners. You probably have to play around with the arrangement of the path components until you get the desired output.
Based on the answer from #nmw, here's some code that works for this:
public class RRDrawable extends Drawable {
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
public RRDrawable(int color) {
paint.setColor(color);
paint.setStyle(Paint.Style.FILL);
}
#Override
public void draw(Canvas canvas) {
int radius = 10; // note this is actual pixels
canvas.drawRoundRect(new RectF(0,0,canvas.getWidth(), canvas.getHeight()), radius, radius, paint);
}
#Override
public void setAlpha(int i) {
//.. not supported
}
#Override
public void setColorFilter(ColorFilter colorFilter) {
//.. not supported
}
#Override
public int getOpacity() {
return 1;
}
}
EDIT: added anti-aliasing to the edges.
(source)
Related
In most of the android applications, the border of the circles are beautiful and the pixels in part of border of the circles are monotonic and beautiful. But when I draw a circle using the following code and when I see the result in my device, the pixels in part of border of the circle is like bitten apple.Such as when an ant has eaten around an apple.
My Code:
class Circle extends View {
Paint paint;
Circle(Context context) {
super(context);
paint = new Paint();
}
#Override
public void onDraw(Canvas canvas) {
paint.setColor(Color.RED);
canvas.drawCircle(50,50,30,paint);
}
}
Turn on antialiasing to achieve it:
paint.setAntiAlias(true);
Please check this demo How to draw a circle in Android
set ANTI_ALIAS_FLAG flag true
For more info you may visit:
https://developer.android.com/reference/android/graphics/Canvas.html
I have an ActionBar icon (the main one on the left, not an action item) that I would like to animate.
I am setting my ActionBar's icon in my Activity like this:
getSupportActionBar().setIcon(icon)
where icon is a Drawable produced by a library that converts a custom XML view into a bitmap. This XML view is a RelativeLayout with a background image and a TextView on top.
Today, when I have to update the TextView I simply re-generate the icon and call setIcon again. Instead, I would like to get a hold of my TextView and apply some animation effect on it, like fade-out and then fade-in after updating it (maybe never having to call setIcon, just re-use the same one).
Not sure how to go about this. Can someone recommend an approach?
EDIT: trying this approach:
In MyActivity:
Drawable myDrawable = new MyDrawable();
supportActionBar.setIcon(myDrawable);
and:
public class MyDrawable extends Drawable {
private Paint paint;
private RectF rect;
public MyDrawable() {
this.paint = new Paint();
this.rect = new RectF();
}
#Override
public void draw(Canvas canvas) {
paint.setARGB(255, 0, 255, 0);
paint.setStrokeWidth(2);
paint.setStyle(Paint.Style.FILL);
rect.right = 20f;
rect.bottom = 20f;
canvas.drawRoundRect(rect, 0.5f, 0.5f, paint);
}
#Override
public void setAlpha(int alpha) {
paint.setAlpha(alpha);
}
#Override
public void setColorFilter(ColorFilter cf) {
paint.setColorFilter(cf);
}
#Override
public int getOpacity() {
return PixelFormat.OPAQUE;
}
}
Nothing shows up. I verified that onDraw gets called. Something suspicious to me is that canvas has both height & width set to 1.
A proper approach for it would be to forget the XML layout and create a custom Drawable.
An instance of this custom drawable will be set to the icon on the ActionBar and call invalidateSelf() whenever necessary to redraw (due to animation, for example).
The drawable can hold reference to other drawables (e.g. BitmapDrawable to have something from the /res/ folder or a Color or Gradient drawable for a background shade) and call (for example) bgDraw.draw(canvas) during the onDraw callback.
It can also draw stuff directly on the canvas that is given to it during onDraw callback. With the canvas you can draw circle, lines, areas, path and text directly on it.
edit:
very simple animation example (didn't check the code, likely typos):
private long animationTime;
public void doAnimation(){
animationTime = System.currentTimeMilis() + 3000; // 3 seconds
invalidateSelf();
}
public void onDraw(Canvas canvas){
// do your drawing.
// You can use difference between
// currentTimeMilis and animationTime for status/position
...
// at the end
if(animationTime > System.currentTimeMilis())
invalidateSelf();
}
I would like to send each time different Drawable shape to view and then add it to my activity.
The problem is I can't find a way to add the drawable shape into the canvas when I'm overriding the onDraw method.
The design supposed to be reusable, I can draw rect first and then draw circle...
I want to find a way to send the view different shape. Is it possible?
#Override
protected void onDraw(Canvas canvas) {
// Draw the ball
ballBounds.set(ballX-ballRadius, ballY-ballRadius, ballX+ballRadius, ballY+ballRadius);
paint.setColor(Color.GREEN);
// canvas.drawOval(ballBounds, paint);
canvas.drawRect(ballBounds, paint);
}
Although, your question needs more explanation on what you need, but with what I could understand is you want rect, or circle on desire, here it is,
Add, global variable int ShapeStructure = 0;
#Override
protected void onDraw(Canvas canvas)
{
// Draw the ball
ballBounds.set(ballX-ballRadius, ballY-ballRadius, ballX+ballRadius, ballY+ballRadius);
paint.setColor(Color.GREEN);
if(ShapeStructure == 0){
canvas.drawOval(ballBounds, paint);
}else{
canvas.drawRect(ballBounds, paint);
}
}
Now that, you have a variable at your disposal, you can control what you want to paint.
Hope, this helps, let me know if you want something else.
I'm trying to Use a BitmapShader to draw on a Canvas. I have 2 images of the same dimensions (one for the alfa channel and one for RGB), that I want to draw on a canvas that was created with the same size. The problem is that it seem as though canvas.drawBitmap users absolute coordinates for the paint. is there a way to draw with relative coordinates.
public class MaskedImageDrawable extends Drawable {
private final Bitmap mMask;
private final Paint mPaint = new Paint();
public MaskedImageDrawable(Bitmap mask, Bitmap image) {
mMask = mask;
Shader targetShader =
new BitmapShader(image, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mPaint.setShader(targetShader);
}
#Override
public void draw(Canvas canvas) {
canvas.drawBitmap(mMask, 0.0f, 0.0f, mPaint);
}
#Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
#Override
public void setAlpha(int alpha) {
mPaint.setAlpha(alpha);
}
#Override
public void setColorFilter(ColorFilter cf) {
mPaint.setColorFilter(cf);
}
}
I can't seem to be able to get the drawable's absolute coordinates on the screen. I know I can use getLocationOnScreen/InWindow from the view that holds the drawable but that doesn't take animations into account.
I tried tried applying relative coordinates by applying a translation on the shader in onBoundsChange but the coordinates here seems to be relative as well.
Matrix mTranslationMatrix = new Matrix()
#Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
mTranslationMatrix.setTranslate(bounds.left, bounds.top);
mPaint.getShader().setLocalMatrix(mTranslationMatrix);
}
As a reference - it seems drawRect with the same paint will use relative coordinates. so replacing the draw method with the following will render the RGB image on the drawable correctly (but not the mask)
#Override
public void draw(Canvas canvas) {
// getBounds returns the relative coordinates as well
canvas.drawRect(getBounds, mPaint);
}
It seems that this is a HW acceleration issue. disabling HW acceleration on the view moves the shader back to relative coordinates.
if (android.os.Build.VERSION.SDK_INT >= 11) {
myView.disableHwAcceleration();
}
ok I'm playing w/ ontouch events extending a view.
what I've done is made a circle on touch.. the cirlce will follow as you move. As you move another circle is made and will sit in the postion decrementing the radius until it disappears.. (right now up to like 10 circles). I can also handle multiple fingers touching at one point in time. Here's the problem.. THE CODE IS NASTY!
To create multiple circle This is my paint method:
public void onDraw(Canvas canvas)
{
paint.setColor(Color.RED);
paint.setStyle(Style.STROKE);
paint.setStrokeWidth(stroke);
canvas.drawCircle(x,y,radius,paint);
canvas.drawCircle(x1,y1,radius1,paint);
canvas.drawCircle(x2,y2,radius2,paint);
canvas.drawCircle(x3,y3,radius3,paint);
canvas.drawCircle(x4,y4,radius4,paint);
canvas.drawCircle(x5,y5,radius5,paint);
canvas.drawCircle(x6,y6,radius6,paint);
paint.setColor(Color.BLUE);
canvas.drawCircle(x7,y7,radius7,paint);
canvas.drawCircle(x8,y8,radius8,paint);
paint.setColor(Color.YELLOW);
canvas.drawCircle(x9,y9,radius9,paint);
canvas.drawCircle(x10,y10,radius10,paint);
}
so as you can see this by far inefficient and makes for some long nasty code.. Part of the issue is the fact I'm bound to only being able to change coordinates in Ontouch.. and invalidate. Anyoone know a way I can do this more efficently (in a more object orriented type approach).
First things first, start with this:
public class Circle {
public int x;
public int y;
public double radius;
public Paint paint;
/* constructors, getters & setters if you feel like ...*/
}
And put all your circles in a
ArrayList<Circle> circles = new ArrayList();
public void onDraw(Canvas canvas)
{
/*...*/
Iterator iterator = circles.iterator();
while(iterator.hasNext()) {
drawCircle(iterator.next());
}
}
public void drawCircle(Canvas canvas, Circle circle) {
canvas.drawCircle(circle.x, circle.y, circle.raidus, circle.paint);
}