我正在实现自定义视图。当用户触摸FrameLayout内部托管的ImageView中的一个点时,我想向FrameLayout添加一堆圆圈。现在,我在半径为20的onDraw方法中绘图。但是,当我将它放入FrameLayout时,它只显示一个小角落。如何告诉自定义视图它的宽度/高度也应该是20?这是我应该在自定义视图中执行的操作,还是在我实例化自定义视图后调用addView的活动中?
public class MyCircle extends View {
Paint paint;
private static final int RADIUS = 20;
public MyCircle(Context context) {
super(context);
paint = new Paint();
paint.setColor(Color.WHITE);
setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
// LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( RADIUS * 2 , RADIUS * 2 );
// setLayoutParams(layoutParams);
}
@Override
public void onDraw( Canvas canvas ) {
canvas.drawCircle(0, 0, RADIUS, paint );
}
}
活动代码基本上是这个(在带有X / Y坐标的onTouch处理程序中调用):
MyCircle circle;
circle = new MyCircle(this);
circle.setX( x );
circle.setY( y );
FrameLayout root = (FrameLayout)findViewById(R.id.image_review_frame);
root.addView( circle );
答案 0 :(得分:2)
覆盖onMeasure()
@Override
protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec)
{
float density = context.getResources().getDisplayMetrics().density;
setMeasuredDimension (RADIUS * density,RADIUS * density);
return;
}
代码重新:密度是将dp转换为像素(例如xhdpi显示密度为2.0)