How can I put Drawable at a specified point on the screen in Android?
Suppose you have a circle figure and you want to install it programmatically at the specified screen coordinates. How to do it?
2 answers
- We take the canvas of the scene.
Draw Drawable on it.
Drawable d = getResources().getDrawable(R.drawable.foobar); d.setBounds(left, top, right, bottom); d.draw(canvas);
Detailed manual , which Drawable to take as a basis.
Or we place any canvas-containing object with the Drawable drawn onto the scene as a descendant, and then we draw into it ( Bitmap ).
Igrostroy: We write the game engine for Android
Specifically about the circle the question has already been here.
Below is a repost from the link:
MyActivity.java :
public class MyActivity extends Activity { public void onCreate(Bundle savedInstanceState) { ... setContentView(new MyView(this,w,h)); } } View.java :
public class MyView extends SurfaceView { public MyView(Context context, int w, int h) { super(context); Canvas grid = new Canvas(Bitmap.createBitmap(h,w, Bitmap.Config.ARGB_8888)); grid. drawColor(Color.WHITE); Paint paint = new Paint(); paint.setStyle(Paint.Style.FILL); grid.drawCircle(w/2, h/2 , w/2, paint); } } What we are doing to not get a black screen without drawing:
protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawCircle(x, y, radius, paint); } |
Can do through Canvas :
canvas.save(); canvas.translate(100, 0); drawable.draw(canvas); canvas.restore(); |