我有自定义视图,在视图中绘制一系列矩形形状。 我已经扩展了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中指定视图的静态宽度和高度。我应该避免吗?
答案 0 :(得分: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;
}