android: how to draw a simple line and display it

2019-06-11 07:19发布

问题:

i want to visualize stuff with a widget by drawing some lines. lets just say i get two coordinates (x,y) every n seconds and then want to update the widget accordingly. this works just fine by now, but now i want to actually DRAW a line between those two points.

i googled around and found many things, but nothing explaining the fundamentals of drawing on an image. since i have NO experience with graphics, i imagine these things to work somehow like graphics drawn with tikzpicture in LaTeX.

can someone please explain to me the how this all works - or at least point me to an example explaining this from the start? it would be highly appreciated!

thanks!

回答1:

In the Android is usually all comes down to drawing on the canvas, e.g. as in the method View.onDraw().

// prepare picture
if (mBackground != null) {
    mBackground.recycle();
}
mBackground = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas backgroundCanvas = new Canvas(mBackground);
backgroundCanvas.scale(width, height);
RectF rect = new RectF(0f, 0f, 1f, 1f);
Paint paint = new Paint();
paint.setFlags(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.parseColor("#18a518")); // gray

// draw line
backgroundCanvas.drawLine(startX, startY, stopX, stopY, paint);

onDraw():

// draw picture on View canvas
@Override
public void onDraw(Canvas canvas) {
    canvas.drawBitmap(mBackground, 0, 0, null);
}

ADD

A primitive chain is as follows: 1 create your own View class (extend). 2 Define onDraw() method in your View. 3 Place your View in layout xml file (or add in runtime: Activity.addContentView()). 4 If needed redraw, call invalidate(); // forces onDraw() to be called.
For detailed information see android examples by google.

Then, if you want improve efficiency, learn SurfaceView. But in surface we drawing on canvas too.



回答2:

http://www.droidnova.com/playing-with-graphics-in-android-part-i,147.html

may help for a start. unfortunately, this still leaves me clueless how to actually DRAW on a widgets layout...

... and to answer this by myself: android: how to add a customized image to widgets?