首页 > 代码库 > 自定义布局RelativeLayout 画网格线
自定义布局RelativeLayout 画网格线
在Android中画线必须由一个载体,要么是一个控件,要么是一个布局,其实他们都是继承自View,通过自定义控件或布局的方式画线是最常见的。下面的小例子实现了在自定义RelativeLayout中画网格线
代码下载:http://download.csdn.net/detail/yxg190221/7589287
自定义控件代码:
</pre><pre name="code" class="java">package layout.layout.ex; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.util.AttributeSet; import android.widget.RelativeLayout; public class GridRelativeLayout extends RelativeLayout { private Canvas myCanvas; private int horGrid = 100, verGrid = 100;//水平网格和竖直网格 private int screenW, screenH;//屏幕宽和高 private boolean initOver = false;//初始化标签 public GridRelativeLayout(Context context) { super(context); setWillNotDraw(false); } public GridRelativeLayout(Context context, AttributeSet attrs) { super(context, attrs); setWillNotDraw(false); } public GridRelativeLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setWillNotDraw(false); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); this.myCanvas = canvas; Paint paint = new Paint(); paint.setColor(android.graphics.Color.YELLOW);//颜色 paint.setStrokeWidth(3);//线宽 int verNum = (int)(screenH / verGrid) + 1; int horNum = (int)(screenW / horGrid) + 1; if (initOver) { for (int i = 0; i < verNum; i++) { canvas.drawLine(0, i * verGrid - 1, screenW, i * verGrid - 1, paint); } for (int i = 0; i < horNum; i++) { canvas.drawLine(i * horGrid - 1, 0, i * horGrid - 1, screenH, paint); } } } /**设置网格线参数**/ public void setInf(int vergrid, int horgrid, int screenW, int screenH) { this.verGrid = vergrid; this.horGrid = horgrid; this.screenW = screenW; this.screenH = screenH; initOver = true; postInvalidate(); } /**擦除网格线**/ public void clearLine() { initOver = false; postInvalidate(); } }主程序代码:
package com.example.test005; import layout.layout.ex.GridRelativeLayout; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity { private GridRelativeLayout rl; private Button btnDraw,btnClear; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); rl=(GridRelativeLayout)findViewById(R.id.rl); btnDraw=(Button)findViewById(R.id.button1); btnClear=(Button)findViewById(R.id.button2); btnDraw.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { rl.setInf(100, 100, 1280, 720);//画网格线 } }); btnClear.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { rl.clearLine();//擦除网格线 } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。