I have problems animating canvas in Zxing Android - android

I have a problema animating a rectangle in Zxing, I am building a qr reader with this library, and my client asked me for an animated laser. No problem for this, laser animation works fine.
But he asked me a texture over laser :/ and I can't animate this.
Sincerely, code for laser is a copy past.
#Override
public void drawLaser(Canvas canvas) {
// Draw a red "laser scanner" line through the middle to show decoding is active
mLaserPaint.setAlpha(155);
int middle = mFramingRect.height() / 2 + mFramingRect.top;
middle = middle + cntr;
if ((cntr < 300) && (!goingup)) {
canvas.drawRect(mFramingRect.left + 2,
middle - 5,
mFramingRect.right - 1,
middle + 10,
mLaserPaint);
cntr = cntr + 4;
}
if ((cntr >= 300) && (!goingup)) goingup = true;
if ((cntr > -300) && (goingup)) {
canvas.drawRect(mFramingRect.left + 4,
middle - 5,
mFramingRect.right - 1,
middle + 10,
mLaserPaint);
cntr = cntr - 4;
}
if ((cntr <= -300) && (goingup)) goingup = false;
postInvalidateDelayed(ANIMATION_DELAY,
mFramingRect.left - POINT_SIZE,
mFramingRect.top - POINT_SIZE,
mFramingRect.right + POINT_SIZE,
mFramingRect.bottom + POINT_SIZE);
}
And my code for trying animate texture over laser
public void drawTexture (Canvas canvas) {
int a = 200;
int b = 220;
int c = 400;
int d = 440;
Paint paint = new Paint();
paint.setColor(Color.RED);
c = c + 100;
d = d + 100;
canvas.drawRect(a,b,c,d,paint);
invalidate();
}
both methods are called in method onDraw
public void onDraw(Canvas canvas) {
if (this.getFramingRect() != null) {
...
this.drawLaser(canvas);
this.drawTexture(canvas);
}
}
I don't know how to animate my rectangle :(, thanks for your help.
Here is my full code
https://gist.github.com/memoadian/2266fbfe6bdf5a3345f2776bdbe7bf2c
UPDATE
Ok, the animation was like this.
public void drawTexture (Canvas canvas) {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.codi_texture);
BitmapShader fillBMPshader = new BitmapShader(bitmap, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
Paint paint = new Paint();
paint.setShader(fillBMPshader);
int middle = mFramingRect.height() / 2 + mFramingRect.top;
middle = middle + cntr;
if ((cntr < 300) && (!goingup)) {
canvas.drawRect(mFramingRect.left,
mFramingRect.top,
mFramingRect.right,
middle,
paint);
cntr = cntr + 4;
}
if ((cntr >= 300) && (!goingup)) goingup = true;
if ((cntr > -300) && (goingup)) {
canvas.drawRect(mFramingRect.left,
mFramingRect.top,
mFramingRect.right,
middle,
paint);
cntr = cntr - 4;
}
if ((cntr <= -300) && (goingup)) goingup = false;
}
And the result is

I'm use lottie for animation and disable laser and transparent rectangle, maybe this could be your next idea
mScannerView.setLaserColor(mContext.getResources().getColor(R.color.btn_color));
mScannerView.setLaserEnabled(false);
mScannerView.setBorderColor(mContext.getResources().getColor(android.R.color.transparent));
mScannerView.setMaskColor(mContext.getResources().getColor(android.R.color.transparent));
List<BarcodeFormat> enableFormat = new ArrayList<>();
enableFormat.add(BarcodeFormat.QR_CODE);
mScannerView.setFormats(enableFormat);
mScannerView.setAutoFocus(true);
try {
int padding = paddingInDp(100);
lottieView.setPadding(-padding, -padding, -padding, -padding);
lottieView.setAnimation("barcode_scan.json");
lottieView.setSpeed(0.5f);
lottieView.playAnimation();
lottieView.loop(true);
} catch (Exception e){
e.printStackTrace();
}

Related

Is it possible to draw a bitmap multiple times with only 2 instances of the bitmap?

I'm trying to understand game-creation in Android. Therefore I try to program a simple TicTacToe without using buttons or layout files. Instead I want to only use bitmaps.
My Problem is that I can create the board, toggle the "X" and "O" symbol correctly, but my onDraw() only draws 2 symbols simultanously at max and I dont quite understand why or how to solve this.
public class GameScreen extends View {
List<TicTacToeSymbol> symbolList = new ArrayList<>();
float posX;
float posY;
int displayWidth;
int displayHeight;
Bitmap background;
Bitmap bitmapX;
Bitmap bitmapO;
Rect dst = new Rect();
boolean touched = false;
TicTacToeSymbol currentSymbol;
TicTacToeSymbol symbolX;
TicTacToeSymbol symbolO;
Grid grid = new Grid();
// Declaring the coordinates for the colums and rows
int ZERO_COLUMN_X = 0;
int FIRST_COLUMN_X = 480;
int SECOND_COLUMN_X = 910;
int THIRD_COLUMN_X = 1425;
(...)
int centerX = 0;
int centerY = 0;
public GameScreen(Context context) {
super(context);
try {
AssetManager assetManager = context.getAssets();
InputStream inputStream = assetManager.open("tictactoegrid.jpg");
background = BitmapFactory.decodeStream(inputStream);
inputStream = assetManager.open("X.png");
bitmapX = BitmapFactory.decodeStream(inputStream);
inputStream = assetManager.open("O.png");
bitmapO = BitmapFactory.decodeStream(inputStream);
inputStream.close();
// I create only 2 symbols, which might be the problem
symbolX = new TicTacToeSymbol(0, 0, 1);
symbolX.setBitmap(bitmapX);
symbolO = new TicTacToeSymbol(0, 0, 2);
symbolO.setBitmap(bitmapO);
setCurrentSymbol(symbolX, 1);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
Display display = this.getDisplay();
Point size = new Point();
display.getSize(size);
displayWidth = size.x;
displayHeight = size.y;
}
public void toggleCurrentSymbol() {
if (currentSymbol == symbolX) {
currentSymbol = symbolO;
} else {
currentSymbol = symbolX;
}
}
public void setCurrentSymbol(TicTacToeSymbol ticTacToeSymbol, int type) {
this.currentSymbol = ticTacToeSymbol;
if (type == 1) {
currentSymbol.setType(1);
} else
currentSymbol.setType(2);
}
public void setCoordinatesCurrentSymbol(int centerX, int centerY) {
currentSymbol.setPosX(centerX);
currentSymbol.setPosY(centerY);
}
#Override
public void onDraw(Canvas canvas) {
dst.set(0, 0, displayWidth, displayHeight - 200);
canvas.drawBitmap(background, null, dst, null);
if (touched) {
// Checking where the user has clicked
// First row
if (posX >= ZERO_COLUMN_X && posX <= FIRST_COLUMN_X
&& posY > ZERO_ROW_Y && posY < FIRST_ROW_Y) {
centerX = FIRST_CENTER_X;
centerY = FIRST_CENTER_Y;
setCoordinatesCurrentSymbol(centerX, centerY);
grid.placeSignInGrid(0, 0, currentSymbol);
toggleCurrentSymbol();
}
if (posX > FIRST_COLUMN_X && posX <= SECOND_COLUMN_X
&& posY > ZERO_ROW_Y && posY < FIRST_ROW_Y) {
centerX = SECOND_CENTER_X;
centerY = FIRST_CENTER_Y;
setCoordinatesCurrentSymbol(centerX, centerY);
grid.placeSignInGrid(1, 0, currentSymbol);
toggleCurrentSymbol();
}
(...)
}
// Go through the grid, get the symbol at the position and add it to the list of symbols
for (int i = 0; i < Grid.GRID_SIZE; i++) {
for (int j = 0; j < Grid.GRID_SIZE; j++) {
if (grid.getSymbolAtField(i, j) != null) {
if (!symbolList.contains(grid.getSymbolAtField(i, j))) {
symbolList.add(grid.getSymbolAtField(i, j));
}
}
}
}
// Draw every symbol in the list.
for (TicTacToeSymbol ttts : symbolList) {
canvas.drawBitmap(ttts.getBitmap(), ttts.getPosX(), ttts.getPosY(), null);
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
touched = true;
posX = event.getX();
posY = event.getY();
invalidate();
return true;
}
return false;
}
}
I create only 2 TicTacToeSymbols, namely symbolXand symbolO. Therefore the symbolList only contains these 2 and draws only those 2.
But how can I draw the same symbol several times? Else I would have to create 9 X-Symbols including the bitmap and 9 O-Symbols to cover all grid-fields with the possible symbols. This would seem wrong / not very elegant?
So how can I draw my 2 symbols several times at the correct positions?
I've looked into several posts like this but could not derive a solution for my problem:
Draw multiple times from a single bitmap on a canvas ... this positions the bitmaps randomly, but I want my symbols on specific positions.

Google mobile vision text API- read specific text with in a recatangle

I am using Google mobile vision text API for reading a text using the APIs provided.
My use cases :
Initially i am drawing a re-sizable rectangle to the surface of view.
Restrict the text that recognize by the google apis only with in the rectangle.
public class GraphicOverlay<T extends GraphicOverlay.Graphic> extends View
{
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
synchronized (mLock)
{
if ((mPreviewWidth != 0) && (mPreviewHeight != 0))
{
mWidthScaleFactor = (float) canvas.getWidth() / (float) mPreviewWidth;
mHeightScaleFactor = (float) canvas.getHeight() / (float) mPreviewHeight;
}
for (Graphic graphic : mGraphics)
{
graphic.draw(canvas);
}
paint.setColor(Color.parseColor("#55000000"));
paint.setStyle(Paint.Style.FILL);
paint.setStrokeJoin(Paint.Join.ROUND);
// mPaint.setStrokeCap(Paint.Cap.ROUND);
paint.setStrokeWidth(5);
canvas.drawPaint(paint);
paint.setColor(Color.parseColor("#55FFFFFF"));
if (groupId == 1) {
mCurrentRect= new Rect(point2.x+colorballs.get(1).getWidthOfBall() / 2,
point4.y +colorballs.get(1).getWidthOfBall() / 2,
point4.x+colorballs.get(1).getWidthOfBall() / 2,
point2.y+colorballs.get(1).getWidthOfBall() / 2);
canvas.drawRect(mCurrentRect, paint);
} else {
mCurrentRect= new Rect(point2.x + colorballs.get(1).getWidthOfBall() / 2,
point4.y + colorballs.get(3).getWidthOfBall() / 2, point4.x
+ colorballs.get(3).getWidthOfBall() / 2, point2.y
+ colorballs.get(1).getWidthOfBall() / 2);
canvas.drawRect(mCurrentRect, paint);
}
BitmapDrawable mBitmap;
mBitmap = new BitmapDrawable();
// draw the balls on the canvas`enter code here`
for (ColorBall ball : colorballs) {
canvas.drawBitmap(ball.getBitmap(), ball.getX(), ball.getY(),
new Paint());
}
}
}
}
class CustomTextRecognizer extends Detector<TextBlock> {
private Detector<TextBlock> mDelegate;
private GraphicOverlay<OcrGraphic> mOcrGraphicOverlay;
CustomTextRecognizer(Detector<TextBlock> delegate, GraphicOverlay<OcrGraphic> ocrGraphicOverlay) {
mDelegate = delegate;
mOcrGraphicOverlay= ocrGraphicOverlay;
}
#Override
public void receiveFrame(Frame frame) {
Bitmap bt= frame.getBitmap();
super.receiveFrame(frame);
}
public SparseArray<TextBlock> detect(Frame frame) {
//How to compare the items that is inside my rectangle.
}
}
/*
* This method will call before each block detection and resolves only with valid detection that
* scanned with in the rectangle provided.
*/
public SparseArray<TextBlock> detect(Frame frame) {
SparseArray<TextBlock> validDetections = new SparseArray<TextBlock>();
Rect overlayRectangle = mOcrGraphicOverlay.getCurrentRectangle();
SparseArray<TextBlock> detectedItems = mDelegate.detect(frame);
for (int index = 0; index < detectedItems.size(); ++index) {
TextBlock detectedBlock = detectedItems.valueAt(index);
Rect boundingBox = detectedBlock.getBoundingBox();
// mOcrGraphicOverlay.getColorball(4).setX(overlayRectangle.left);
// mOcrGraphicOverlay.getColorball(4).setY(overlayRectangle.top);
/* if(((overlayRectangle.top <boundingBox.top) &&
(overlayRectangle.top+overlayRectangle.height())> (boundingBox.top +boundingBox.height())) &&
((overlayRectangle.left <boundingBox.left) &&
(overlayRectangle.left+overlayRectangle.width())> (boundingBox.left +boundingBox.width())))*/
mOcrGraphicOverlay.getColorball(4).setX(boundingBox.left);
mOcrGraphicOverlay.getColorball(4).setY(boundingBox.top);
if ((overlayRectangle.top < boundingBox.top) &&
(overlayRectangle.top + overlayRectangle.height()) > (boundingBox.top + boundingBox.height())) {
validDetections.put(index, detectedBlock);
}
}
return validDetections;
}
Found one solution.

Android - Canvas Black when using Flood-Fill

When I implement my flood-fill class it turns my entire Bitmap black. Obviously this is not the desired effect. I've looked at the following threads:
https://stackoverflow.com/questions/24030858/flood-fill-is-coloring-my-entire-screen
Flood Fill Algorithm Resulting in Black Image
flood fill coloring on android
From what I can see I'm doing everything they've come up with in those solutions, however it hasn't led me to a solution for my problem. So to cut to the chase, here's the code with some brief explanations.
XML
I am using a relative layout and positioning (stacking) two ImageViews directly on top of each other. They both have the same image and this creates the illusion of you being able to draw on the image. However, you are in fact simply drawing on a transparent overlay.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
....
<ImageView
android:id="#+id/drawContainer2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toRightOf="#id/imageMapperSurfaces"
android:contentDescription="#string/image" />
<ImageView
android:id="#+id/drawContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toRightOf="#id/imageMapperSurfaces"
android:contentDescription="#string/image" />
...
</RelativeLayout>
Canvas
Then I create my Canvas with this code and I make sure to set my layer types correctly.
public void setCanvas() {
if(mFile != null && mFile.exists()) {
mPictureBitmap = BitmapFactory.decodeFile(mFile.getAbsolutePath());
mBitmap = Bitmap.createScaledBitmap(mPictureBitmap, mImageView.getWidth(), mImageView.getHeight(), false);
mPictureBitmap = mBitmap.copy(Bitmap.Config.ARGB_8888, true);
mBitmap = mPictureBitmap.copy(Bitmap.Config.ARGB_8888, true);
mSceneBitmap = mBitmap.copy(Bitmap.Config.ARGB_8888, true);
mBlurBitmap = blurImage(mPictureBitmap);
mCanvas = new Canvas(mBitmap);
mImageView.setImageBitmap(mBitmap);
mImageView2.setImageBitmap(mPictureBitmap);
mBlur.setImageBitmap(mBlurBitmap);
// failure to set these layer types correctly will result in a black canvas after drawing.
mImageView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
mImageView2.setLayerType(View.LAYER_TYPE_HARDWARE, null);
mImageView.bringToFront();
mAllowedToDraw = true;
setImageViewOnTouch();
}
}
Flood-Fill Implementation
I grab the color, pass my params to the flood-fill object, use the flood-fill method, return the bitmap, and finally draw the new bitmap to my canvas.
int targetColor = mSceneBitmap.getPixel((int) event.getX(), (int) event.getY());
FloodFill fill = new FloodFill(mBitmap, targetColor, Color.argb(100, 255, 0, 0));
fill.floodFill((int) event.getX(), (int) event.getY());
Bitmap bmp = fill.getImage();
mCanvas.drawBitmap(bmp, 0, 0, null);
mImageView.invalidate();
Flood-Fill Class
The boiler-plate Flood-fill algorithm.
public class FloodFill {
protected Bitmap mImage = null;
protected int[] mTolerance = new int[] { 0, 0, 0, 0 };
protected int mWidth = 0;
protected int mHeight = 0;
protected int[] mPixels = null;
protected int mFillColor = 0;
protected int[] mStartColor = new int[] { 0, 0, 0, 0 };
protected boolean[] mPixelsChecked;
protected Queue<FloodFillRange> mRanges;
public FloodFill(Bitmap img) {
copyImage(img);
}
public FloodFill(Bitmap img, int targetColor, int newColor) {
useImage(img);
setFillColor(newColor);
setTargetColor(targetColor);
}
public void setTargetColor(int targetColor) {
mStartColor[0] = Color.red(targetColor);
Log.v("Red", "" + mStartColor[0]);
mStartColor[1] = Color.green(targetColor);
Log.v("Green", "" + mStartColor[1]);
mStartColor[2] = Color.blue(targetColor);
Log.v("Blue", "" + mStartColor[2]);
mStartColor[3] = Color.alpha(targetColor);
Log.v("Alpha", "" + mStartColor[3]);
}
public int getFillColor() {
return mFillColor;
}
public void setFillColor(int value) {
mFillColor = value;
}
public int[] getTolerance() {
return mTolerance;
}
public void setTolerance(int[] value) {
mTolerance = value;
}
public void setTolerance(int value) {
mTolerance = new int[] { value, value, value, value };
}
public Bitmap getImage() {
return mImage;
}
public void copyImage(Bitmap img) {
mWidth = img.getWidth();
mHeight = img.getHeight();
mImage = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(mImage);
canvas.drawBitmap(img, 0, 0, null);
mPixels = new int[mWidth * mHeight];
mImage.getPixels(mPixels, 0, mWidth, 0, 0, mWidth, mHeight);
}
public void useImage(Bitmap img) {
mWidth = img.getWidth();
mHeight = img.getHeight();
mImage = img;
mPixels = new int[mWidth * mHeight];
mImage.getPixels(mPixels, 0, mWidth, 0, 0, mWidth, mHeight);
}
protected void prepare() {
mPixelsChecked = new boolean[mPixels.length];
mRanges = new LinkedList<FloodFillRange>();
}
public void floodFill(int x, int y) {
// Setup
prepare();
if (mStartColor[0] == 0) {
// ***Get starting color.
int startPixel = mPixels[(mWidth * y) + x];
mStartColor[0] = (startPixel >> 16) & 0xff;
mStartColor[1] = (startPixel >> 8) & 0xff;
mStartColor[2] = startPixel & 0xff;
}
LinearFill(x, y);
FloodFillRange range;
while (mRanges.size() > 0) {
range = mRanges.remove();
int downPxIdx = (mWidth * (range.Y + 1)) + range.startX;
int upPxIdx = (mWidth * (range.Y - 1)) + range.startX;
int upY = range.Y - 1;
int downY = range.Y + 1;
for (int i = range.startX; i <= range.endX; i++) {
if (range.Y > 0 && (!mPixelsChecked[upPxIdx]) && CheckPixel(upPxIdx)) LinearFill(i, upY);
if (range.Y < (mHeight - 1) && (!mPixelsChecked[downPxIdx]) && CheckPixel(downPxIdx)) LinearFill(i, downY);
downPxIdx++;
upPxIdx++;
}
}
mImage.setPixels(mPixels, 0, mWidth, 0, 0, mWidth, mHeight);
}
protected void LinearFill(int x, int y) {
int lFillLoc = x;
int pxIdx = (mWidth * y) + x;
while (true) {
mPixels[pxIdx] = mFillColor;
mPixelsChecked[pxIdx] = true;
lFillLoc--;
pxIdx--;
if (lFillLoc < 0 || (mPixelsChecked[pxIdx]) || !CheckPixel(pxIdx)) {
break;
}
}
lFillLoc++;
int rFillLoc = x;
pxIdx = (mWidth * y) + x;
while (true) {
mPixels[pxIdx] = mFillColor;
mPixelsChecked[pxIdx] = true;
rFillLoc++;
pxIdx++;
if (rFillLoc >= mWidth || mPixelsChecked[pxIdx] || !CheckPixel(pxIdx)) {
break;
}
}
rFillLoc--;
FloodFillRange r = new FloodFillRange(lFillLoc, rFillLoc, y);
mRanges.offer(r);
}
protected boolean CheckPixel(int px) {
int red = (mPixels[px] >>> 16) & 0xff;
int green = (mPixels[px] >>> 8) & 0xff;
int blue = mPixels[px] & 0xff;
int alpha = (Color.alpha(mPixels[px]));
return (red >= (mStartColor[0] - mTolerance[0]) && red <= (mStartColor[0] + mTolerance[0])
&& green >= (mStartColor[1] - mTolerance[1]) && green <= (mStartColor[1] + mTolerance[1])
&& blue >= (mStartColor[2] - mTolerance[2]) && blue <= (mStartColor[2] + mTolerance[2])
&& alpha >= (mStartColor[3] - mTolerance[3]) && alpha <= (mStartColor[3] + mTolerance[3]));
}
protected class FloodFillRange {
public int startX;
public int endX;
public int Y;
public FloodFillRange(int startX, int endX, int y) {
this.startX = startX;
this.endX = endX;
this.Y = y;
}
}
}
So that's it, we should have all the pieces to the puzzle but for some reason they aren't working. I'm at a loss and any help is appreciated. Thanks!
I think you're line:
mCanvas.drawBitmap(bmp, 0, 0, null);
might need to be more like
mPaint = new Paint();
mCanvas.drawBitmap(bmp, 0, 0, mPaint);
I am not sure at everything but as far as I can tell you I would try with these solutions:
First:
instead of using decodeFile I rather use decodeInputStream
Second:
As someone has anwsered You better use a Paint() when showing the view
Third:
I am going to ask why do you need that food-fill alghorithm? I think it's too laggy and It looks a little messy to use, why dont you create a new scaled bitmap or something like an opengl effect to do it? because that is the reason why there are graphics cards;

How to optimize drawing text on canvas

I have window with 3 circles, they are rotating simultaneously. Everything is good until a Add text to the circles, then the rotation starts to lagging.
How can i optimize drawing on canvas ?
This is my code:
#Override
protected void onDraw(final Canvas canvas) {
if (mPaint == null) {
mPaint = new Paint();
mPaint.setTextSize(20f);
}
drawUpperCircle(canvas);
drawBottomCircle(canvas);
drawMainCircle(canvas);
try {
Thread.sleep(1, 1);
invalidate();
mRotation += 0.9;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onDraw(canvas);
}
private void drawUpperCircle(Canvas canvas) {
canvas.save();
canvas.rotate(mRotation, 0, mUpperCircleCentr);
mPaint.setColor(Color.CYAN);
canvas.drawCircle(0, mUpperCircleCentr, mUpperCirclRadius, mPaint);
mPaint.setColor(Color.BLACK);
for (int i = 0; i < SEG_COUNT; i++) {
canvas.rotate(SEG_IN_GRAD, 0, mUpperCircleCentr);
canvas.drawLine(0, mUpperCircleCentr, mUpperCirclRadius, mUpperCircleCentr, mPaint);
// canvas.drawText("my text" + String.valueOf(i), mUpperCirclRadius * 2 / 3, mUpperCircleCentr - 4, mPaint);
}
canvas.restore();
}
private void drawBottomCircle(Canvas canvas) {
canvas.save();
canvas.rotate(mRotation, 0, mBottomCircleCentr);
mPaint.setColor(Color.RED);
canvas.drawCircle(0, mBottomCircleCentr, mBottomCirclRadius, mPaint);
mPaint.setColor(Color.BLACK);
for (int i = 0; i < SEG_COUNT; i++) {
canvas.rotate(SEG_IN_GRAD, 0, mBottomCircleCentr);
canvas.drawLine(0, mBottomCircleCentr, mBottomCirclRadius, mBottomCircleCentr, mPaint);
// canvas.drawText("my text" + String.valueOf(i), mBottomCirclRadius * 2 / 3, mBottomCircleCentr - 4, mPaint);
}
canvas.restore();
}
private void drawMainCircle(Canvas canvas) {
canvas.save();
canvas.rotate(mRotation, 0, mMainCircleCentr);
mPaint.setColor(Color.argb(100, 100, 100, 100));
canvas.drawCircle(0, mMainCircleCentr, mMainCirclRadius, mPaint);
mPaint.setColor(Color.BLACK);
for (int i = 0; i < SEG_COUNT; i++) {
canvas.rotate(SEG_IN_GRAD, 0, mMainCircleCentr);
canvas.drawLine(0, mMainCircleCentr, mMainCirclRadius, mMainCircleCentr, mPaint);
canvas.drawText("my text" + String.valueOf(i), mMainCirclRadius * 2 / 3, mMainCircleCentr - 4, mPaint);
}
canvas.restore();
}
EDIT
To improve performance and remove drawing from UI thread I have Used Double Buffering With SurfaceView and implement #Morgans optimizations. That is how it realized.
DrawView.java
public class DrawView extends SurfaceView implements SurfaceHolder.Callback {
...............................................................
public DrawView(Context context, AttributeSet attrs) {
super(context, attrs);
getHolder().addCallback(this);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float currentX = event.getX();
float currentY = event.getY();
float deltaX, deltaY;
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
// Modify rotational angles according to movement
deltaX = currentX - previousX;
deltaY = currentY - previousY;
mDrawThread.mRotation += deltaY * 180 / getHeight();
}
// Save current x, y
previousX = currentX;
previousY = currentY;
return true; // Event handled
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height) {
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
mDrawThread = new DrawThread(getHolder(), this);
mDrawThread.setRunning(true);
mDrawThread.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
boolean retry = true;
mDrawThread.setRunning(false);
while (retry) {
try {
mDrawThread.join();
retry = false;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
And the main work is done in the DrawThread.java
public class DrawThread extends Thread {
private ArrayList<Path> mMainCirclePaths = new ArrayList<Path>(SEG_COUNT);
private ArrayList<Path> mUpperCirclePaths = new ArrayList<Path>(SEG_COUNT);
private ArrayList<Path> mCenterCirclePaths = new ArrayList<Path>(SEG_COUNT);
private ArrayList<Path> mBottomCirclePaths = new ArrayList<Path>(SEG_COUNT);
private boolean mRun = false;
private SurfaceHolder mSurfaceHolder;
private DrawView mDrawView;
private Paint mPaint;
private CirclesModel mCirclesModel;
public float mRotation = 0;
public DrawThread(SurfaceHolder surfaceHolder, DrawView drawView) {
mSurfaceHolder = surfaceHolder;
mDrawView = drawView;
mCirclesModel = new CirclesModel(mDrawView.getHeight());
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setTextSize(18f);
initPaths();
}
public void setRunning(boolean b) {
mRun = b;
}
#Override
public void run() {
while (mRun) {
Canvas canvas = null;
try {
canvas = mSurfaceHolder.lockCanvas(null);
synchronized (mSurfaceHolder) {
drawMainCircle(canvas);
mPaint.setColor(Color.WHITE);
canvas.drawCircle(mCirclesModel.mMainCircleCentr[CirclesModel.X], mCirclesModel.mMainCircleCentr[CirclesModel.Y],
mCirclesModel.mSmallCirclesRadius, mPaint);
drawCenterCircle(canvas);
drawUpperCircle(canvas);
drawBottomCircle(canvas);
//mRotation += 0.5f;
}
} finally {
if (canvas != null) {
mSurfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
private void drawMainCircle(Canvas canvas) {
canvas.save();
canvas.rotate(mRotation, mCirclesModel.mMainCircleCentr[CirclesModel.X], mCirclesModel.mMainCircleCentr[CirclesModel.Y]);
float rot = mRotation;
mPaint.setColor(Color.LTGRAY/* argb(100, 255, 255, 255) */);
canvas.drawCircle(mCirclesModel.mMainCircleCentr[CirclesModel.X], mCirclesModel.mMainCircleCentr[CirclesModel.Y],
mCirclesModel.mBigCirclesRadius, mPaint);
mPaint.setColor(Color.BLACK);
for (int i = 0; i < SEG_COUNT; i++) {
canvas.rotate(SEG_IN_GRAD, mCirclesModel.mMainCircleCentr[CirclesModel.X], mCirclesModel.mMainCircleCentr[CirclesModel.Y]);
rot += SEG_IN_GRAD;
float absRot = Math.abs(rot % 360);
if (absRot > mCirclesModel.mMainCircleSegment[0] && absRot < mCirclesModel.mMainCircleSegment[1]) {
continue;
}
canvas.drawLine(mCirclesModel.mMainCircleCentr[CirclesModel.X], mCirclesModel.mMainCircleCentr[CirclesModel.Y],
mCirclesModel.mBigCirclesRadius, mCirclesModel.mMainCircleCentr[CirclesModel.Y], mPaint);
canvas.drawPath(mMainCirclePaths.get(i), mPaint);
// canvas.drawText("my text" + String.valueOf(i),
// mMainCirclRadius * 2 / 3, mMainCircleCentr - 4, mPaint);
}
canvas.restore();
}
.................................................................
}
Double Buffering is implemented in the two lines of code
canvas = mSurfaceHolder.lockCanvas(null); here I take from surface view canvas in which i will draw next frame.
mSurfaceHolder.unlockCanvasAndPost(canvas); here I am overlaping current image on SurfaceView with new canwas, this is the moment where image changes. Be aware if you have transparent elements then the previous image will be still visible, Image is not replaced, but overlaped.
Below is a version of your code that contains a few optimizations.
First, I try not to draw the lines and text that currently offscreen. I do this by tracking the rotation angle, and skipping the drawing for net rotations between 90 and 270 degrees. On my 2.3 simulator this improved performance overall by 25%.
Second, I "cache" the strings I am going to draw by initializing an array (ArrayList<Path>) with one Path for each string I need to draw. I do this in the same place you were one-time initializing the mPaint. Then I draw the strings using canvas.drawPath(...). On my 2.3 simulator this improved performance by another 33%. The net effect was to about double the rotation speed. Also, it stopped the text from "wiggling around".
A few other notes:
I removed the Thread.sleep(1,1). Not sure exactly what you were trying to accomplish with that.
I changed rotation delta to 1.0 from 0.9. Not sure why you were using 0.9. Note that if you change to back, my "log time it takes to rotate 10 degrees" will not quite work since mRotation % 10 may seldom be 0.
On a 4.1 simulator, the rotation was generally much faster (about 4x) than on my 2.3 simulator. And a 4.1 device was faster yet.
public class AnimView extends View {
Paint mPaint;
ArrayList<Path> mTextPaths;
float mRotation = 0f;
float mUpperCircleCentr = 150f;
float mUpperCirclRadius = 150f;
private static final int SEG_COUNT = 60;
private static final float SEG_IN_GRAD = 360.0f / SEG_COUNT;
float mBottomCircleCentr = 450f;
float mBottomCirclRadius = 150f;
float mMainCircleCentr = 300f;
float mMainCirclRadius = 300f;
long mLastMillis = 0L;
// ctors removed
#Override
protected void onDraw(final Canvas canvas) {
super.onDraw(canvas);
if (mPaint == null) {
mPaint = new Paint();
mPaint.setTextSize(20f);
// init text paths
mTextPaths = new ArrayList<Path>(SEG_COUNT);
for (int i = 0; i < SEG_COUNT; i++) {
Path path = new Path();
String s = "my text" + String.valueOf(i);
mPaint.getTextPath(s, 0, s.length(), mMainCirclRadius * 2 / 3, mMainCircleCentr - 4, path);
path.close(); // not required on 2.2/2.3 devices
mTextPaths.add(path);
}
}
if (mLastMillis == 0L) {
mLastMillis = System.currentTimeMillis();
}
drawUpperCircle(canvas);
drawBottomCircle(canvas);
drawMainCircle(canvas);
invalidate();
if (((int) mRotation) % 10 == 0) {
long millis = System.currentTimeMillis();
Log.w("AnimateCanvas", "OnDraw called with mRotation == " + mRotation);
Log.w("AnimateCanvas", "Last 10 degrees took millis: " + (millis - mLastMillis));
mLastMillis = millis;
}
}
private void drawUpperCircle(Canvas canvas) {
canvas.save();
canvas.rotate(mRotation, 0, mUpperCircleCentr);
float rot = mRotation;
mPaint.setColor(Color.CYAN);
canvas.drawCircle(0, mUpperCircleCentr, mUpperCirclRadius, mPaint);
mPaint.setColor(Color.BLACK);
for (int i = 0; i < SEG_COUNT; i++) {
canvas.rotate(SEG_IN_GRAD, 0, mUpperCircleCentr);
rot += SEG_IN_GRAD;
if (rot % 360 > 90 && rot % 360 < 270)
continue;
canvas.drawLine(0, mUpperCircleCentr, mUpperCirclRadius, mUpperCircleCentr, mPaint);
}
canvas.restore();
}
private void drawBottomCircle(Canvas canvas) {
canvas.save();
canvas.rotate(mRotation, 0, mBottomCircleCentr);
float rot = mRotation;
mPaint.setColor(Color.RED);
canvas.drawCircle(0, mBottomCircleCentr, mBottomCirclRadius, mPaint);
mPaint.setColor(Color.BLACK);
for (int i = 0; i < SEG_COUNT; i++) {
canvas.rotate(SEG_IN_GRAD, 0, mBottomCircleCentr);
rot += SEG_IN_GRAD;
if (rot % 360 > 90 && rot % 360 < 270)
continue;
canvas.drawLine(0, mBottomCircleCentr, mBottomCirclRadius, mBottomCircleCentr, mPaint);
}
canvas.restore();
}
private void drawMainCircle(Canvas canvas) {
canvas.save();
canvas.rotate(mRotation, 0, mMainCircleCentr);
float rot = mRotation;
mPaint.setColor(Color.argb(100, 100, 100, 100));
canvas.drawCircle(0, mMainCircleCentr, mMainCirclRadius, mPaint);
mPaint.setColor(Color.BLACK);
for (int i = 0; i < SEG_COUNT; i++) {
canvas.rotate(SEG_IN_GRAD, 0, mMainCircleCentr);
rot += SEG_IN_GRAD;
if (rot % 360 > 90 && rot % 360 < 270)
continue;
canvas.drawLine(0, mMainCircleCentr, mMainCirclRadius, mMainCircleCentr, mPaint);
canvas.drawPath(mTextPaths.get(i), mPaint);
// canvas.drawText("my text" + String.valueOf(i), mMainCirclRadius * 2 / 3, mMainCircleCentr - 4, mPaint);
}
canvas.restore();
}
}
Your code is pretty nice and simple. You can optimize it by using less loops for instance, drawing things all together or combining variables, but this would quickly get messy.
I would recommend you to keep your drawing code more or less equal. You actually don't do the worst thing : instanciating objects, and it's clear and easy to maintain.
But you could maybe try to use a double buffer : drawing in a buffer in ram and flipping the buffer one shot on the screen. This generally performs quite well to get a constant animation pace. Use locking and unlocking of your canvas : Double buffering in Java on Android with canvas and surfaceview

How to drawing a path with a bitmap?

I have a little drawing app and want to use "complex" shapes as brushes, i.e. a star.
Drawing with a simple brush already works with this code:
remotePath.reset();
remotePath.moveTo(start_x, start_y);
float dx = Math.abs(end_x - start_x);
float dy = Math.abs(end_y - start_y);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
remotePath.quadTo(start_x, start_y, (end_x + start_x) / 2, (end_y + start_y) / 2);
}
remotePath.lineTo(end_x, end_y);
// commit the path to our offscreen
mCanvas.drawPath(remotePath, remotePaint);
// kill this so we don't double draw
remotePath.reset();
invalidate();
I basically want the same functionality using this bitmap:
Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.brush_star);
My solution currently is using a list of points (coordinates) to draw the bitmap. The problem with that solution is that it only draws bitmaps at the given points resulting in having gaps between each drawn bitmap. I rather would like to get a smooth line while drawing like with a simple brush without any gaps in between.
Current code for the bitmap drawing:
protected void onDraw(Canvas canvas) {
// Make canvas white
canvas.drawColor(Color.WHITE);
// Paintable area
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.drawPath(mPath, mPaint);
for (Point point : points) {
canvas.drawBitmap(complexBrush, point.x, point.y, p);
}
}
What's the best way to do so?
Thanks for any help!
I use this
Point's class:
public class Point implements Serializable {
float x, y;
float dx, dy;
}
Paint object:
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(5);
paint.setColor(Color.RED);
paint.setAntiAlias(true);
draw on canvas:
private void drawCanvas(Canvas canvas, List<Point> pts){
if (pts.size() > 1){
Path path = new Path();
final int SMOOTH_VAL = 6;
for(int i = pts.size() - 2; i < pts.size(); i++){
if(i >= 0){
Point point = pts.get(i);
if(i == 0){
Point next = pts.get(i + 1);
point.dx = ((next.x - point.x) / SMOOTH_VAL);
point.dy = ((next.y - point.y) / SMOOTH_VAL);
}
else if(i == pts.size() - 1){
Point prev = pts.get(i - 1);
point.dx = ((point.x - prev.x) / SMOOTH_VAL);
point.dy = ((point.y - prev.y) / SMOOTH_VAL);
}
else{
Point next = pts.get(i + 1);
Point prev = pts.get(i - 1);
point.dx = ((next.x - prev.x) / SMOOTH_VAL);
point.dy = ((next.y - prev.y) / SMOOTH_VAL);
}
}
}
boolean first = true;
for(int i = 0; i < pts.size(); i++){
Point point = pts.get(i);
if(first){
first = false;
path.moveTo(point.x, point.y);
}
else{
Point prev = pts.get(i - 1);
path.cubicTo(prev.x + prev.dx, prev.y + prev.dy, point.x - point.dx, point.y - point.dy, point.x, point.y);
}
}
canvas.drawPath(path, paint);
} else {
if (pts.size() == 1) {
Point point = pts.get(0);
canvas.drawCircle(point.x, point.y, 2, paint);
}
}
}
Draw on bitmap canvas:
private void drawBitmap(Bitmap bmp, List<Point> pts) {
Canvas c = new Canvas(bmp);
drawCanvas(c, pts);
}

Categories

Resources