Android 2D Graphics(First Step)
This is first entry of Android 2D Graphics.
In pure Java, we use Graphics Context of AWT to draw shapes.
How about Android? Similar.
First, creating View class and override onDraw method.
AWT review
public void paint( Graphics g ) { Graphics2D g2 = (Graphics2D)g; Ellipse2D e = new Ellipse2D.Doule(x,y, w, h); g2.setPaint(Color.gray); g2.fill(e); g2.setPaint(Color.black); g2.draw(e); }
This is a part of code. Get Graphics convert from it to Graphics2D.
It’s ready.
Android View
View! This is key point.
And use Canvas to draw objects in View.
Sample(Frame)
public class DrawView extends View { public DrawView ( Context context ) { super(context); } @Override protected void onDraw ( Canvas canvas ) { //super.onDraw(canvas); // Draw something } }
All draw process is in onDraw method.
Sample(draw circle)
public class DrawView extends View { private Paint paint; private RectF rect; public DrawView ( Context context ) { super(context); paint = new Paint(); rect = new RectF(0f, 0f, 100f, 100f); // left, top, right, bottom } @Override protected void onDraw ( Canvas canvas ) { //super.onDraw(canvas); canvas.drawColor(Color.WHITE); // Background color // If use new instance, // new RectF(0f, 0f, 100f, 100f) // Avoid object allocations during draw paint.setStyle(Paint.Style.FILL); paint.setColor(Color.BLUE); canvas.drawOval(rect, paint); } }
Paint is a kind of Pen. AWT has similar thing.
At first, creating pen in constructor and
Warning!
If you create any instances in onDraw, “Avoid object allocations during draw” is coming.
onDraw is called every time display requires drawing.
Operation is fine, if you are care of it, create instance in other place.
Test in Activity
For test, I’ll show you onCreate of Activity.
@Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); addContentView(new DrawView(this), new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); }
This is a really good read for me, Must admit that you are one of the best bloggers I ever saw.Thanks for posting this informative article.
This is a really good read for me, thank you!
Hey! This is my first comment here so I just wanted to give a quick shout out and say I really enjoy reading your blog posts. Can you recommend any other blogs/websites/forums that deal with the same subjects? Thank you so much!
info, but great topic. I needs to