I'm trying to animate a background in a game I'm making.
https://imgur.com/kQGWsLu
Should look like this(terrible recording quality)
My first attempt work well on my phone but a lot of people saw their fps cut in half:
public void draw(Canvas canvas, Paint paint) {
if (mPaint == null) {
mPaint = new Paint();
mPaint.setColor(Color.GRAY);
mPaint.setStrokeWidth(1);
mPaint.setAntiAlias(true);
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setShader(new RadialGradient(canvas.getWidth() / 4, canvas.getHeight() / 3,
Math.max(1, canvas.getHeight() / 2), Color.rgb(5, 12, 127), Color.rgb(32, 36, 100), Shader.TileMode.REPEAT));
}
width = canvas.getWidth();
height = canvas.getHeight();
canvas.save();
rotation += 4;
if (rotation > 360)
rotation = 0;
canvas.rotate(rotation, width / 2, height / 2);
canvas.drawCircle(width / 2, height / 2, height * 1.3f, mPaint);
canvas.restore();
}
So now I'm thinking about of pre rendering a image and drawing it as a bitmap that covers the screen and rotates instead. I also cut the calculations to only update every other frame instead.
public void draw(Canvas canvas, Paint paint) {
if (!initiated) {
centerX = (int) (canvas.getWidth() / 2);
centerY = (int) (canvas.getHeight() / 2);
width = (int) (canvas.getWidth() * 2f);
height = (int) (canvas.getHeight() * 2f);
map = factory.GFX().getBackground();
initiated = true;
}
if (!skipUpdate) {
x = CalculatorService.getXCircle(rotation, distance, centerX);
y = CalculatorService.getYCircle(rotation, distance, centerY);
body.set((int) x - width / 2,
(int) y - height / 2,
(int) x + (width / 2),
(int) y + (height / 2));
rotation += rotationSpeed;
if (rotation > 360)
rotation = 0;
}
skipUpdate = !skipUpdate;
canvas.drawBitmap(map, null, body, paint);
}
Though since the image is small in size 320*320 I had to scale it up and draw it bigger then the screen to avoid it moving out of bounds and showing the basic black background, and I'm not sure if this is really a improvement, do anyone have a better way of doing it or any advice on how I can improve?
Related
I am using drawTextOnPath() to create a bent text like in given picture below but I can't figure out how to rotate the text?
What I want is below highlighted in picture with arrow and circle.
What i have been able to achieve is below
So I just want to rotate these texts?
You can achieve the result you want without drawTextOnPath() using:
float radius = 300;
float cx = getWidth() / 2; //Center of the circle
float cy = getHeight() / 2; //Center of the circle
for (int degree = 0; degree < 360; degree += 30) {
canvas.save();
canvas.translate(cx, cy);
canvas.rotate(degree);
String text = "" + degree;
float textCenterX = radius + textPaint.measureText(text) / 2;
float textCenterY = 0 - textPaint.getTextSize() / 2;
if (degree < 180) {
canvas.rotate(-90, textCenterX, textCenterY);
} else {
canvas.rotate(+90, textCenterX, textCenterY);
}
canvas.drawText("" + degree, radius, 0, textPaint);
canvas.restore();
}
You just need to flip the canvas and draw on it
canvas.save()
canvas.scale(1, -1, width / 2, height / 2)
// your drawing code
canvas.restore()
This is how my custom drawable looks by default.
But when scrolled, it overlaps with the AppBarLayout.
The code for the Drawable goes like this:
#Override
public void draw(#NonNull Canvas canvas) {
// get drawable dimensions
Rect bounds = getBounds();
float width = bounds.right - bounds.left;
float height = bounds.bottom - bounds.top;
float w2 = width / 2;
float h2 = height / 2;
float radius = Math.min(w2, h2) - mStrokeWidth / 2;
mPath.reset();
mPath.addCircle(width / 2, height / 2, radius, Path.Direction.CW);
canvas.clipPath(mPath);
// draw background gradient
float barHeight = height / themeColors.length;
mRectF.left = 0;
mRectF.top = 0;
mRectF.right = width;
mRectF.bottom = height;
for (int i = 0; i < themeColors.length; i++) {
mPaint.setColor(themeColors[i]);
canvas.drawRect(0, i * barHeight, width, (i + 1) * barHeight, mPaint);
}
mRectF.set(0, 0, width, height);
canvas.clipRect(mRectF, Region.Op.REPLACE);
if (mStrokeWidth != 0)
canvas.drawCircle(width / 2, height / 2, width / 2 - mStrokeWidth / 2, mStrokePaint);
}
Support Library Version: 25.3.1, 26.1.0
What I've tried:
- Different Region values for clipping path instead of REPLACE
- Clipping path rectangle first and then clipping circle.
How do I fix this ?
I am posting my solution as answer.
The reason it was getting overlapped was because the canvas was getting clipped twice without saving it.
I removed this statement:
canvas.clipRect(mRectF, Region.Op.REPLACE);
and before clipping the canvas for the first time
i saved its state using
canvas.save();
canvas.clipPath(mPath);
and then when i was drawing the stroke, i need the original canvas so i restored it
canvas.restore();
if (mStrokeWidth != 0)
canvas.drawCircle(width / 2, height / 2, width / 2 - mStrokeWidth / 2, mStrokePaint);
This fixed the issue.
Final Drawable Code:
#Override
public void draw(#NonNull Canvas canvas) {
// get drawable dimensions
Rect bounds = getBounds();
float width = bounds.right - bounds.left;
float height = bounds.bottom - bounds.top;
float w2 = width / 2;
float h2 = height / 2;
float radius = Math.min(w2, h2) - mStrokeWidth / 2;
mPath.reset();
mPath.addCircle(width / 2, height / 2, radius, Path.Direction.CW);
canvas.save();
canvas.clipPath(mPath);
// draw background gradient
float barHeight = height / themeColors.length;
mRectF.left = 0;
mRectF.top = 0;
mRectF.right = width;
mRectF.bottom = height;
for (int i = 0; i < themeColors.length; i++) {
mPaint.setColor(themeColors[i]);
canvas.drawRect(0, i * barHeight, width, (i + 1) * barHeight, mPaint);
}
mRectF.set(0, 0, width, height);
//canvas.clipRect(mRectF, Region.Op.REPLACE);
canvas.restore();
if (mStrokeWidth != 0)
canvas.drawCircle(width / 2, height / 2, width / 2 - mStrokeWidth / 2, mStrokePaint);
}
I have view in which, I want to display a heart that is filled based on percentage shown in middle of heart.
I tried canvas, was able to draw heart but could not partial fill, used cliprect,etc but could not achieve this, please see Image
Now if its 30 %, then only 30% area from bottom should be filled with redcolor rest should be white, also the color outside of heart is blue which needs to be same way always as shown in image.
int percentage = 85;
int w = 100;
int h = 100;
Bitmap bitmap = Bitmap.createBitmap(w,h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
Path path = new Path();
// Fill the canvas with background color
canvas.drawColor(Color.BLUE);
paint.setShader(null);
float width = 100.00f;
float height =100.00f;
// Starting point
path.moveTo(width / 2, height / 5);
// Upper left path
path.cubicTo(5 * width / 14, 0,
0, height / 15,
width / 28, 2 * height / 5);
// Lower left path
path.cubicTo(width / 14, 2 * height / 3,
3 * width / 7, 5 * height / 6,
width / 2, height);
// Lower right path
path.cubicTo(4 * width / 7, 5 * height / 6,
13 * width / 14, 2 * height / 3,
27 * width / 28, 2 * height / 5);
// Upper right path
path.cubicTo(width, height / 15,
9 * width / 14, 0,
width / 2, height / 5);
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.FILL);
// draw text percentage
Paint textPaint = new Paint();
textPaint.setColor(Color.BLACK);
textPaint.setTextAlign(Paint.Align.CENTER);
textPaint.setTextSize(12);
int xPos = (canvas.getWidth() / 2);
int yPos = (int) ((canvas.getHeight() / 2) - ((textPaint.descent() + textPaint.ascent()) / 2)) ;
//((textPaint.descent() + textPaint.ascent()) / 2) is the distance from the baseline to the center.
canvas.drawText(percentage+" % ", xPos, yPos, textPaint);
int heightOfClip = 100 - percentage;
//clip
canvas.clipRect(0,0,100,heightOfClip, Region.Op.XOR);
// draw heart and color it
canvas.drawPath(path, paint);
// draw text percentage
canvas.drawText(percentage+"%", xPos, yPos, textPaint);
mSampleIv.setImageBitmap(bitmap);
I'm trying to draw an arc inside a circle to represent the temperature, but I'm having a difficult time achieving that. During my search I found those solutions
This one I couldn't understand what is the scale method for, and is drawing more than one arch, which confused me a bit
This post gave it a fixed size where I need the size to be controlled by the custom view in my XML layout
From here I understood the concept the degrees but I didn't understand how to determine the oval size
What i reached so far
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int startTop = 0;
int startLeft = 0;
int endBottom = getHeight() / 2;
int endRight = endBottom;// This makes an equal square.
int centerX = getWidth() / 2;
int centerY = getHeight() / 2;
int upperEdgeX = (int) (centerX + getWidth() / 2 * Math.cos(270 * Math.PI / 180));
int upperEdgeY = (int) (centerY + getWidth() / 2 * Math.sin(270 * Math.PI / 180));
int bottomEdgeX = (int) (centerX + getWidth() / 2 * Math.cos(90 * Math.PI / 180));
int bottomEdgeY = (int) (centerY + getWidth() / 2 * Math.sin(90 * Math.PI / 180));
int leftEdgeX = (int) (centerX + getWidth() / 2 * Math.cos(180 * Math.PI / 180));
int leftEdgeY = (int) (centerY + getWidth() / 2 * Math.sin(180 * Math.PI / 180));
int rightEdgeX = (int) (centerX + getWidth() / 2 * Math.cos(0 * Math.PI / 180));
int rightEdgeY = (int) (centerY + getWidth() / 2 * Math.sin(0 * Math.PI / 180));
RectF rect = new RectF(startTop, startLeft, endRight, endBottom);
canvas.drawCircle(centerX, centerY, getWidth() / 2, mBasePaint);
canvas.drawCircle(centerX, centerY, getWidth() / 3, mCenterPaint); // White circle
}
UPDATE:
I need my view to be like a Donut Pie chart where the middle will hold the degree
UPDATE 2:
I'm trying to have something like this
The following custom View draws two arcs connecting to form a circle as well as an inner circle.
Moreover, I let it fill the rectangle used for drawing the arc and use a yellow background for the View, the activity background is dark. (These additional features are meant for getting a better impression of how drawing a circle / an arc works, they can help with debugging.)
The custom View:
public class MySimpleView extends View{
private static final int STROKE_WIDTH = 20;
private Paint mBasePaint, mDegreesPaint, mCenterPaint, mRectPaint;
private RectF mRect;
private int centerX, centerY, radius;
public MySimpleView(Context context) {
super(context);
init();
}
public MySimpleView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MySimpleView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init()
{
mRectPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mRectPaint.setColor(ContextCompat.getColor(getContext(), R.color.magenta));
mRectPaint.setStyle(Paint.Style.FILL);
mCenterPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mCenterPaint.setColor(ContextCompat.getColor(getContext(), R.color.white));
mCenterPaint.setStyle(Paint.Style.FILL);
mBasePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mBasePaint.setStyle(Paint.Style.STROKE);
mBasePaint.setStrokeWidth(STROKE_WIDTH);
mBasePaint.setColor(ContextCompat.getColor(getContext(), R.color.blue));
mDegreesPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mDegreesPaint.setStyle(Paint.Style.STROKE);
mDegreesPaint.setStrokeWidth(STROKE_WIDTH);
mDegreesPaint.setColor(ContextCompat.getColor(getContext(), R.color.green));
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// getHeight() is not reliable, use getMeasuredHeight() on first run:
// Note: mRect will also be null after a configuration change,
// so in this case the new measured height and width values will be used:
if (mRect == null)
{
// take the minimum of width and height here to be on he safe side:
centerX = getMeasuredWidth()/ 2;
centerY = getMeasuredHeight()/ 2;
radius = Math.min(centerX,centerY);
// mRect will define the drawing space for drawArc()
// We have to take into account the STROKE_WIDTH with drawArc() as well as drawCircle():
// circles as well as arcs are drawn 50% outside of the bounds defined by the radius (radius for arcs is calculated from the rectangle mRect).
// So if mRect is too large, the lines will not fit into the View
int startTop = STROKE_WIDTH / 2;
int startLeft = startTop;
int endBottom = 2 * radius - startTop;
int endRight = endBottom;
mRect = new RectF(startTop, startLeft, endRight, endBottom);
}
// just to show the rectangle bounds:
canvas.drawRect(mRect, mRectPaint);
// subtract half the stroke width from radius so the blue circle fits inside the View
canvas.drawCircle(centerX, centerY, radius - STROKE_WIDTH / 2, mBasePaint);
// Or draw arc from degree 192 to degree 90 like this ( 258 = (360 - 192) + 90:
// canvas.drawArc(mRect, 192, 258, false, mBasePaint);
// draw an arc from 90 degrees to 192 degrees (102 = 192 - 90)
// Note that these degrees are not like mathematical degrees:
// they are mirrored along the y-axis and so incremented clockwise (zero degrees is always on the right hand side of the x-axis)
canvas.drawArc(mRect, 90, 102, false, mDegreesPaint);
// subtract stroke width from radius so the white circle does not cover the blue circle/ arc
canvas.drawCircle(centerX, centerY, radius - STROKE_WIDTH, mCenterPaint);
}
}
consider two circles with (0,0) as center and 110 and 210 as radius respectively...
i.e i have CENTER as (0,0) and CIRCLE 1 radius as 110 and CIRCLE 2 radius as 210.
Now i need to move an object tball in between these two circles.
Here is my code--
public void run() {
while (isitok == true) {
// perform drawing
if (!holder.getSurface().isValid()) {
continue;
}
Canvas canvas = holder.lockCanvas();
canvas.drawARGB(255, 150, 150, 10);
// System.out.println("Canvas matrix -" + canvas.getm));
Paint p = new Paint();
// canvas.drawBitmap(tball, (x - tball.getWidth()) / 2,
// (y - tball.getHeight()) / 2, p);
p.setStyle(Paint.Style.STROKE);
p.setColor(Color.WHITE);
p.setColor(Color.parseColor("#0101DF"));
canvas.drawCircle(canvas.getWidth() / 2,
canvas.getHeight() / 2, 60, p);
canvas.drawCircle(canvas.getWidth() / 2,
canvas.getHeight() / 2, 110, p);
float x = (canvas.getWidth() / 2) - (tball.getWidth() / 2);
float y = (canvas.getHeight() / 2) - 110 + (110 - 60) / 2
- (tball.getHeight() / 2);
canvas.drawBitmap(tball, x, y, p);
float movingpts[];
holder.unlockCanvasAndPost(canvas);
}
}
Circle coordinates are
X = MX + R * cos( angle )
Y = MY + R * sin( angle )
where (MX,MY) is the center or midpoint of the circle and R the radius. For screen coordinates it is sometimes better to use
Y = MY - R * sin( angle )
to get the angle consistent with mathematical conventions on circle orientation.