search

Home  >  Q&A  >  body text

android - 自定义View继承ImageView,需要创建一个bitmap,如何获取width和height?

PHPzPHPz2773 days ago720

reply all(3)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 17:04:54

    Since onDraw() will be called frequently, it is not recommended to create a new object instance in this method.

    Your problem may be that you don’t know how to correctly obtain the size of the View. The obtained width and height are always 0.

    I’m going to tell you the simplest way, so let’s use it as a starting point

    Use view.post()

    public class CustomView extends View {
        private Bitmap mBitmap;
    
        public CustomView(Context context) {
            super(context)
            
            ...
            
            this.post(new Runnable() {
                @Override
                public void run() {
                    mBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
                }
            });
        }
    }

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 17:04:54

    You can use View.onLayout or ViewTreeObserver

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 17:04:54

    Since you inherit ImageView, I think you will naturally use the setImageBitmap(), setImageDrawable and other methods of ImageView, so you can get the width and height in these methods or get the bitmap directly

    reply
    0
  • Cancelreply