以编程方式设置方块的半径

时间:2014-10-10 16:59:33

标签: android android-imageview

我设计自定义布局中的任何正方形扩展ImageView但是我找不到任何关于如何设置半径或圆形正方形的文档,我的正方形就像这样:

enter image description here

但我需要这样:

enter image description here

我的代码:

public class GameView extends ImageView {
    private Paint paint;
    private Paint textPaint;
    private int with;
    private int height;
    private int[][] cells = new int[4][4];
    public GameView(Context context) {
        super(context);
        initialize();
    }

    public GameView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialize();
    }

    public GameView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initialize();
    }

    public void initialize(){
        paint = new Paint();
        paint.setColor(Color.parseColor("#afafaf"));
        paint.setStyle(Paint.Style.FILL_AND_STROKE);
        paint.setAntiAlias(true);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int size = with / 4;
        int padding = 5;
        for ( int i=0; i < 4 ; i++)
        {
            for( int j=0; j < 4 ; j++){
                Rect rect = new Rect( i*size + padding , j*size + padding , (i+1) *size - padding, (j+1)*size - padding );
                canvas.drawRect(rect, paint);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

这就是你所要做的。在drawable文件夹中,创建一个名为rounded_rect.xml的xml文件:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle"> 

    <solid android:color="#afafaf"/>    

    <stroke android:width="3dp"
        android:color="#ffafafaf"/>

    <padding android:left="5dp"
         android:top="5dp"
         android:right="5dp"
         android:bottom="5dp"/> 

    <corners android:radius="5px"/> 
</shape>

然后在包含ImageView的xml中,将该属性应用于ImageView

android:src="@drawable/rounded_rect"

我没有测试过这个,如果它不起作用,请告诉我,我会做一些修改。