android自定义视图重绘

时间:2013-02-24 09:45:16

标签: android view

我正在尝试在onCreate()方法

中重绘自定义视图
public void onCreate(Bundle savedInstanceState)    
{    
        super.onCreate(savedInstanceState);    
        setContentView(R.layout.main);    
        circleView = (CircleView)findViewById(R.id.circleView);    
        circleView.setCircle(100, 100, 25);    
        circleView.wrapView();    
 }    

和自定义视图是:

public class CircleView extends View  
{  
    private Paint paint = null;  
    private int x = 50;  
    private int y = 50;  
    private int radius = 50;  
    public CircleView(Context context, AttributeSet attrs)   
    {  
        super(context, attrs);  
        init();  
    }  
    public CircleView(Context context)    
    {  
        super(context);  
        init();  
    }  
    private void init()  
    {  
        paint = new Paint();  
    }   
    public void setCircle(int x, int y, int radius)  
    {  
        this.x = x;  
        this.y = y;  
        this.radius = radius;  
        init();  
        this.invalidate();  
    }  
    @Override  
    protected void onDraw(Canvas canvas)   
    {  
        super.onDraw(canvas);  
        paint.setColor(Color.WHITE);  
        canvas.drawCircle(x, y, radius, paint);  
        Log.e("", "radius : " + radius);  
    }  
        public void setColor(int color)  
    {  
        paint.setColor(color);  
    }  
    public void wrapView()   
    {  
        this.setLayoutParams(new RelativeLayout.LayoutParams(radius*2, radius*2));  
        this.invalidate();  
    }  
}

和xml是:

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/layoutMain"
    >

    <com.pep1439.view.CircleView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/circleView" />

</RelativeLayout>

我只想调整圆圈的大小,但失败了。帮我画任意半径的圆圈。这该怎么做。如果我使用默认值,它的工作正常。当我删除行circleView.setCircle(100, 100, 25);时,它会绘制圆圈。我想在运行时调整圆圈。 感谢。

1 个答案:

答案 0 :(得分:1)

您将xy设为100,将半径设为25。然后,您将视图的大小调整为radius*250,最后您只在25的位置上绘制一个半径为100,100的圆圈50x50大小。换句话说:您在视图区域之外绘制圆圈