开发者

How to redraw an optionsmenu-icon with canvas

I'm trying to get a option开发者_StackOverflowsmenu-icon inside onPrepareOptionsMenu in my Activity an redraw it with the help of canvas:

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);

      MenuItem item = menu.findItem(R.id.menuCart);

      Drawable icon = item.getIcon();
      Bitmap bitmap = Bitmap.createBitmap(icon.getIntrinsicWidth(),
               icon.getIntrinsicHeight(),
               Bitmap.Config.ARGB_8888);
      Canvas c = new Canvas(bitmap);
      c.drawColor(Color.BLUE);
      Paint paint = new Paint();
      paint.setColor(Color.WHITE);
      paint.setAntiAlias(true);
      paint.setStyle(Style.FILL_AND_STROKE);
      c.drawCircle(5, 5, 50, paint);
      icon.draw(c);
      icon.invalidateSelf();
      item.setIcon(icon);

      return true;
}

Unfortunately nothing is happening. There is the same icon-image in the menu like before. Could someone tell me what is wrong with the code i am using?


In these two lines:

c.drawCircle(5, 5, 50, paint);
icon.draw(c);

you are drawing first a circle then the icon into the Cavas c, which is derived from the Bitmap 'bitmap', hence your new graphics is now in 'bitmap' which should be set as the new icon. Try this:

item.setIcon(new BitmapDrawable(bitmap));


new BitmapDrawable(bitmap) is deprecated.

Updated to new BitmapDrawable(getResources(), bitmap))

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜