Is android.graphics.Paint
memory heavy object? Which one is more efficient, to pass paint object refrence to classes that need to draw on canvas and set paint properties such as color, style, etc. in those classes, or create new Paint object wherever it's needed?

- 43,021
- 16
- 133
- 222
-
1Can down-voter please explain why he/she down-voted? I asked this question because i used to do drawing and animating(basically game development) with LibGDX. LibGDX uses SpriteBatch object which is very memory-heavy objecy. I wonder is it the same with Paint object? – Thracian Dec 27 '16 at 13:36
2 Answers
Yes, Paint
is heavy, especially its creation and initialization. Does this mean you have to reuse the same Paint
object for everything? Well, it depends.
If you are going to perform multiple drawText()
but with different color, then you can reuse the same paint but with different color (using setColor()
). But if you are going to perform two unrelated operation(drawing) in two different classes and there are major differences in the Paint configuration like Color, font size, Style, PathEffect, etc... then it's better to have separate Paint objects for them.
In short, use the same paint for performing similar drawing with less differences. And use different paint objects for performing unrelated drawing with major differences. Hope this helps.

- 17,490
- 7
- 63
- 98
-
1It's precisely what i was looking for. Thanks, it will benefit greatly to me. Would you mind explaining why it's heavy? I – Thracian Jan 04 '17 at 14:22
-
Take a look at `Paint.java`. It is backed up by a `native` paint. So when you create new Paint objects, you are also creating the native objects as well. – Henry Jan 09 '17 at 03:49
-
3`setColor` is time consuming operation. I'm not sure if your approach is actually efficient. Here is a nice article: https://medium.com/rosberryapps/make-your-custom-view-60fps-in-android-4587bbffa557 – Mussa May 16 '19 at 15:22
For me best way is: Create new Paint for each object with different style or width or color. And for draw text create other paints. (If you want draw to text with different color or text size create new paint to)
This way create your code more lazy for other developer, because one paint draws one object, it is good OOP style ))).

- 956
- 8
- 22
-
1https://developer.android.com/training/custom-views/custom-drawing Official documentation does exactly this. Wander if this is efficient enough. – Mussa May 16 '19 at 15:20