How to draw circle with alpha gradient on canvas? - android

How to draw on canvas like this pic with alpha gradient?

Please specify next time whether you mean the android app canvas or HTML5 canvas on android browsers. If its the former, use android-canvas. This solution is in JS since its easier to show, and will work fine on either platform.
Gradients along paths in canvas are hard. The easiest way is to fudge it.
Instead of thinking of your image as a gradient that follows a circular path, think of it as two linear gradients.
One on the left side, going from green to gray, top to bottom.
The other on the right side, going from white to gray, top to bottom.
Imagine a square made of those two gradients:
Now imagine a circle cutting through:
That's all you gotta do.
To "cut" through like that its easiest to use clipping regions, so I've made an example doing that.
Here's the live example: http://jsfiddle.net/simonsarris/Msdkv/
Code below:
var greenPart = ctx.createLinearGradient(0,0,0,100);
greenPart.addColorStop(0, 'palegreen');
greenPart.addColorStop(1, 'lightgray');
var whitePart = ctx.createLinearGradient(0,0,0,100);
whitePart.addColorStop(0, 'white');
whitePart.addColorStop(1, 'lightgray');
var width = 20;
ctx.lineWidth = width;
// First we make a clipping region for the left half
ctx.save();
ctx.beginPath();
ctx.rect(-width, -width, 50+width, 100 + width*2);
ctx.clip();
// Then we draw the left half
ctx.strokeStyle = greenPart;
ctx.beginPath();
ctx.arc(50,50,50,0,Math.PI*2, false);
ctx.stroke();
ctx.restore(); // restore clipping region to default
// Then we make a clipping region for the right half
ctx.save();
ctx.beginPath();
ctx.rect(50, -width, 50+width, 100 + width*2);
ctx.clip();
// Then we draw the right half
ctx.strokeStyle = whitePart;
ctx.beginPath();
ctx.arc(50,50,50,0,Math.PI*2, false);
ctx.stroke();
ctx.restore(); // restore clipping region to default

Related

OpenGL ES drawing dotted circular line circle

How to draw a circular line circle like this image?
How to achieve or any suggestions?
Not essential, but I'd like to draw it on Android.
You can draw this by simply drawing colored rectangles. Either create a method to draw a rect and call it for each of the rectangles or create a buffer holding all the vertex data and call it once.
For the first procedure the easiest way is using matrices. Assume you are drawing a rectangle at angle of height and width with some inner circle radius. Now all you need is a single rect vertex buffer as:
{
0.0, -0.5,
0.0, 0.5,
1.0, -0.5,
1.0, 0.5
}
This represents a 1x1 cube which is positioned perfectly to draw a line. Now to use matrices we want to identity which would draw the line in the center of your screen. Then rotate it to whatever angle you need, then move it forward so it is outside of the inner circle and in the end scale it to whatever size you need:
Matrix4x4 matrix = Matrix4x4.identity // Start with identity
matrix = matrix.rotate(angle, 0, 0, 1) // Rotate around Z
matrix = matrix.translate(radius, 0, 0) // Translate it forward, this is not a bug
matrix = matrix.scale(height, width, 1.0) // Scale it
This should be it. Now if you want to add some performance on drawing you should have a single draw call so you create a single buffer. You may still use exactly the same procedure but transform original vertex data by a target matrix on CPU and then pack the result into array.
I am not sure from your image if the bottom (inner) part of lines needs to be circular. To achieve this the easiest way would be to draw to alpha mask first and then use it in blending. To achieve this you need to clear color to (1,1,1,1). Then draw a circle only on alpha channel using color mask (FALSE, FALSE, FALSE, TRUE) and blending (ONE, ONE) then using a any transparent color like (0,0,0,0). This will make your background completely white but there will be a circle in the middle with zero alpha. So now reset back to default mask settings using (TRUE, TRUE, TRUE, TRUE) and start drawing your rectangles with blending (DST_ALPHA, ONSE_MINUS_DST_ALPHA). This should cut your rectangles nicely to show a correct circle in the middle.
Some more robust procedures exist for the same thing like drawing to stencil buffer instead of alpha channel.

Android canvas Drawable position translation

I Created my custom view in which i placed one drawable, I need to change its position. I have 2 Rectangles(Rect) which have the top, bottom left, right. Now I need to give translation effect by Changing Rect.
Lets suppose Rect1 have top = 100 & Rect2 have top = 200. So I need to do translation from 100 to 200 with anim duration.
Any help is appreciated.

Android Canvas Paint Arc Border

I am drawing an arc with a border by painting two arcs, one over the other the first being slightly larger.
The issue is with "slightly larger" this can end up with the border not always being even all the way round.
Both the arcs I am drawing have the same radius, I simply make it larger by adding a degree to the start and two degrees to the end (necessary to ensure the borders on either end of the arc are equal) and increasing the stroke width.
In the supplied picture the thicker border edge is the smallest I can possibly make it while it is still visible. (-1 degree off the inner arc)
I have considered drawing the arc outline with four separate calls two straight lines for either end and two arcs. This seems quite inefficient for what I want to achieve.
I am wondering if anyone has any suggestions about how else I could draw a border thats even, minimizing the number of draw/canvas rotation calls if possible.
Relevant code sample for current solution:
Paint mOutlinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
Paint mFillPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mFillPaint.setStyle(Style.STROKE);
mFillPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
mFillPaint.setColor(Color.TRANSPARENT);
mFillPaint.setStrokeWidth(mValueWidth);
mOutlinePaint.setStyle(Style.STROKE);
mOutlinePaint.setStrokeWidth(mBorderWidth);
mOutlinePaint.setColor(Color.WHITE);
mRect.set(mHalfXSubRadius, mHalfYSubRadius, mHalfXAddRadius, mHalfYAddRadius);
canvas.drawArc(mRect, ARC_START-1, MAX_ARC+2, false, mOutlinePaint);
canvas.drawArc(mRect, ARC_START, MAX_ARC, false, mFillPaint);
U shouldnt make your arc bigger, instead try to draw the same sized arc (in white), X pixel right,down,up,left,corners as well (total of 8 drawings).
where X is the border size u want.
after that draw the main arc (in gray) in the middle.
psuedo code:
paint=white;
drawArc(x,y+2);
drawArc(x,y-2);
drawArc(x+2,y+2);
drawArc(x+2,y-2);
drawArc(x-2,y+2);
drawArc(x-2,y+2);
drawArc(x+2,y);
drawArc(x-2,y);
paint=gray;
drawArc(x,y);

Using a gradient along a path

I'm trying to create a 'glow' effect using the Android Path class. However, the gradient is not being warped to fit around the path. Instead, it is simply being display 'above' it and clipped to the path's stroke. Using a square path, the image below shows what I mean:
Instead, that should look more like this:
In other words, the gradient follows the path, and in particular wraps around the corners according to the radius set in the CornerPathEffect.
Here is the relevant part of the code:
paint = new Paint();
paint.setStyle(Style.STROKE);
paint.setStrokeWidth(20);
paint.setAntiAlias(true);
LinearGradient gradient = new LinearGradient(30, 0, 50, 0,
new int[] {0x00000000, 0xFF0000FF, 0x00000000}, null, Shader.TileMode.MIRROR);
paint.setShader(gradient);
PathEffect cornerEffect = new CornerPathEffect(10);
paint.setPathEffect(cornerEffect);
canvas.drawPath(boxPath, paint);
Any ideas?
Another alternative is to get a 'soft-edged brush' effect when defining the stroke width. I've experimented with BlurMaskFilters, but those give a uniform blur rather than a transition from opaque to transparent. Does anyone know if that's possible?
How about drawing with a soft brush bitmap? Make a soft circular brush with opacity decreasing radially outward using image editing software like Photoshop. Save as drawable, load it in a bitmap and draw it evenly spaced along your path. Make the bitmap with white coloured brush. This way you can simply multiply the given colour(Here blue) to your bitmap using PorterDuffColorFilter.
brush1=BitmapFactory.decodeResource(getResources(), R.drawable.brush_custom_one);
//This contains radially decreasing opacity brush
porter_paint.setColorFilter(new PorterDuffColorFilter(paint.getColor(), Mode.MULTIPLY));
for (int i=1;i<matrix.size();i++) {
//matrix contains evenly spaced points along path
Point point = matrix.get(matrix.get(i));
canvas.drawBitmap(brush1, point.x,point.y, porter_paint);}
The brush used is (It's there):
The final result is:
Turns out there was a stupidly obvious way of doing this. Simply re-use the same path, and adjust the stroke width and alpha on each drawing pass. Example code:
float numberOfPasses = 20;
float maxWidth = 15;
for (float i = 0; i <= numberOfPasses; i++){
int alpha = (int) (i / numberOfPasses * 255f);
float width = maxWidth * (1 - i / numberOfPasses);
paint.setARGB(alpha, 0, 0, 255);
paint.setStrokeWidth(width);
canvas.drawPath(path, paint);
}
See below for an example of the result. The left path was drawn using this method, the right path, for comparison, is drawn in a single stroke with maxWidth and 255 alpha.
This mainly works. There are two problems:
The gradient isn't as smooth as it could be. This is because each pass being drawn over the previous one results in the alpha building up too quickly, reaching 255 before the final strokes. Experimenting a bit with the line int alpha = (int) (i / numberOfPasses * 125f); (note the change to 125f rather than 255f) helps.
The path looks like it has been 'cut' on the insides of the corners. Probably some result of the CornerPathEffect applied.
What you're wanting to do, if I understand it right, is to have the gradient effectively form a "brush" for the stroke.
This is exactly what I also was trying to achieve recently, but as far as I can tell the API doesn't provide any straightforward means to do it. I have recently created an SVG to Android Canvas converter class and so I am working a lot in Inkscape lately, too. So, when I was looking into it, I wondered if it's even possible to do it in Inkscape. However, even in Inkscape it's a very non-trivial thing to do. After some searching I eventually came across this image of a gradient being applied along the course of a path, together with a download link for a tutorial beneath:
http://www.flickr.com/photos/35772571#N03/3312087295/
What I was personally trying to do at the time was to create some semi-circles where the path is a kind of neon glow as opposed to a flat colour. Talking in terms of both the Android API and the SVG standard, it seems that the only way to to do this is to create a radial gradient that's centred perfectly on the circle, and position a series of color stops in exactly the right places. Pretty tricky to do, and I certainly don't know how you'd do it to a shape like a square.
Sorry that this is a bit of a 'I couldn't do it either' rather than a useful answer! I'll follow this with interest as I'm eager to know a solution for a kind of 'soft brush' effect too.
Can be very complicated to draw a gradient than follow a path.
So I suggest you to use some library already done than make it for you.
One can be Sc-Gauges.
Have some usefully classe than you can use for your goal.
For first include the library:
dependencies {
...
compile 'com.github.paroca72:sc-gauges:3.0.7'
}
After create an image or what you want with a canvas where draw:
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
Now the code:
// Dimensions
int padding = 24;
Rect drawArea = new Rect(padding, padding, 700 - padding, 500 - padding);
// Get the main layout
ImageView imageContainer = (ImageView) this.findViewById(R.id.image);
assert imageContainer != null;
// Create a bitmap and link a canvas
Bitmap bitmap = Bitmap.createBitmap(
drawArea.width() + padding * 2, drawArea.height() + padding * 2,
Bitmap.Config.ARGB_8888
);
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(Color.parseColor("#f5f5f5"));
// Create the path building a bezier curve from the left-top to the right-bottom angles of
// the drawing area.
Path path = new Path();
path.moveTo(drawArea.left, drawArea.top);
path.quadTo(drawArea.centerX(), drawArea.top, drawArea.centerX(), drawArea.centerY());
path.quadTo(drawArea.centerX(), drawArea.bottom, drawArea.right, drawArea.bottom);
// Feature
ScCopier copier = new ScCopier();
copier.setPath(path);
copier.setColors(Color.RED, Color.GREEN, Color.BLUE);
copier.setWidths(20);
copier.draw(canvas);
// Add the bitmap to the container
imageContainer.setImageBitmap(bitmap);
And this the result:
The first part of the code is just for create a bitmap where draw.
What you interest is the second part where use ScCopier.
Just give the path, the color and the with.
Note than is you are inside a view you can use onDraw for draw directly on the view canvas.
This library can used to create gauge of every kind.
If you want take a look to this site ScComponents have some free and not gauges components.

Android screen coordinate system : how to set (0,0) at the bottom left side of android screen as first quadrent of xy plane

how to set the screen coordinate system of android screen as first Quadrant of the XY plane
,iwant the (0,0) position to be at bottom left , and i wanna know if i can use the trignometric equation on android screen as Android XY plane is not like the Xy plane
I don't think there's a way to do it that would affect the entire system, such as the XML layout files. But if you just want to draw with a Canvas, you can use translate() and scale().
First use translate() to slide the canvas down so 0,0 is at the bottom. Now the top of the screen would be a negative number, so call scale() to flip it around. Now 0,0 is still at the bottom, and the top of the screen is a positive number.
I'm working with information from this answer and its comments. Use something like:
canvas.save(); // need to restore after drawing
canvas.translate(0, canvas.getHeight()); // reset where 0,0 is located
canvas.scale(1, -1); // invert
... // draw to canvas here
canvas.restore(); // restore to normal
And yes, you can use normal 2D trigonometric functions with the XY coords. You can do it even if they're not translated, you just have to think it through more carefully.
I don't know that you're going to have much luck changing where (0,0) is located, but you could set a constant that accounts for such. myY = y minus screenHeight so (x, myY) adjusts y to the bottom of the screen and works from there +/-.
look up canvas.scale(xs,ys,xp,yp)
xp and yp are the new coordinates that you set for your (0,0) point.

Categories

Resources