Setting font type for live wallpaper causes screen to go black
I have this code
void drawText2(Canvas c)
{
DisplayMetrics metrics = new DisplayMetrics开发者_JAVA百科();
Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
display.getMetrics(metrics);
int screenwidth = metrics.widthPixels;
int screenheight = metrics.heightPixels;
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.BLACK);
paint.setTextSize(150);
paint.setAntiAlias(true);
paint.setTypeface(Typeface.DEFAULT_BOLD);
Bitmap.createBitmap(100, 100, Bitmap.Config.RGB_565);
float x = screenwidth/2;
float y = screenheight/2;
c.drawText("32", x, y, paint);
}
Which works fine, but if I add in the following line
Typeface GC=Typeface.createFromAsset(getAssets(),"fonts/ADarling.ttf");
as well as change the line
paint.setTypeface(Typeface.DEFAULT_BOLD);
to
paint.setTypeface(Typeface.create(GC, 0));
It will use the font and everything seems to be working fine, but randomly the wallpaper will go black, and stay that way for a few minutes then it will appear again, and will continue to do this. Am I using the code wrong?
Try to initialize the font once only(do not load it everytime drawText2()
called)
private Typeface myFont;
public myConstructor() {
/* ... */
Typeface GC = Typeface.createFromAsset(getAssets(),"fonts/ADarling.ttf");
myFont = Typeface.create(GC, Typeface.NORMAL);
/* ... */
}
void drawText2(Canvas c)
/* ... */
paint.setTypeface(myFont);
/* ... */
}
Also the following line is not needed:
Bitmap.createBitmap(100, 100, Bitmap.Config.RGB_565);
Heres a wild stab in the dark:)
You should check that your code for setting the font is in the same thread as the initialization code for the font.
There are some known issues in this area, especially if you are setting up things in java then usings the NDK to adjust the font. This is because Java and the NDK operate in slightly different threads, and a thread safe memory allocation system is used.
Just a thought, which may not apply to you.
Tony
精彩评论