0

我有自定义视图,它在视图中绘制一系列矩形形状。我扩展了 View 并覆盖了 onDraw 方法。

这是构造函数(仅添加重要部分)

 public CustomDrawableView(Context mContext , AttributeSet attr)
    {
        super(mContext,attr);

        //setMeasuredDimension(measuredWidth, measuredHeight)
        Log.e("CustomDrableView", "widht"+attr.getAttributeName(5));
        Log.e("CustomDrableView", "widht2"+attr.getAttributeValue(5));



        mColors = new int[] {
            //color codes
            };


        mColors_state_init = new int[]
                {
                    //color codes
                };

        mPaint = new Paint();
        mPaint.setAntiAlias(true);

        mPaint2 = new Paint(mPaint);
        mPaint2.setAlpha(64);

        float[] radii = {15,15,15,15,15,15,15,15};
        mDrawable = new ShapeDrawable(new RoundRectShape(radii, null, null));


       // mDrawable.getPaint().setColor(0xff74AC23);
        ShapeDrawable prev = mDrawable;
        mDrawables = new ShapeDrawable[15];

        for (int i = 0; i < 15; i++) {
            mDrawables[i] = new ShapeDrawable(new RoundRectShape(radii, null, null));
        }
}

这是 onDraw

protected void onDraw(Canvas canvas) {       
     mDrawable.setBounds(x, y, x + width, y + height);
      for (int i = 0; i < 15; i++) {

        mDrawables[i].getPaint().setColor(0xff74AC23);
        mDrawables[i].setDither(true);
        mDrawables[i].setBounds(x, y + (i *20), x+width, y+height+(i*20));
      }


    for(int i = 0 ; i < 15 ; i++)
    {
         ColorFilter filter = null;

         if (mColors[i] == 0) {
                    filter = null;
                } else {
                    filter = new PorterDuffColorFilter(mColors_test[i],
                            PorterDuff.Mode.SRC_ATOP);


        }


             mDrawables[i].setColorFilter(filter);
             mDrawables[i].draw(canvas);
    }

宽度和高度值必须随着不同的屏幕尺寸而变化。我怎样才能做到这一点?

我正在为 xml 中的视图指定静态宽度和高度。我应该避免这种情况吗?

4

1 回答 1

0

首先,是的,您应该避免在 xml 中设置静态宽度和高度,让它们成为 wrap_content。然后,而不是这样做

 float[] radii = {15,15,15,15,15,15,15,15}; 

根据 screenSize 找到 15 的等效值。为此,您应该获得屏幕尺寸。获得 screenSizes 后,您可以按比例调整大小。它可能是这样的:

 int calculatedValue = screenWidth * 15 / 320;    // I assume 320 as a default screen width here
 float[] radii = {calculatedValue, calculatedValue, calculatedValue, calculatedValue, calculatedValue, calculatedValue, calculatedValue, calculatedValue}

以防万一,如果您不知道如何获取屏幕尺寸...这里有一个片段:

 public void GetDimensions() {
    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    width = metrics.widthPixels;
    height = metrics.heightPixels;
}
于 2012-10-19T21:20:09.410 回答