好久没写博客了,最近终于心静下来了,踏实学习干活了.
Region意思是区域,范围.先了解有啥api给我们使用,然后每个api啥意思,我们就可以根据这个做出我们想要的效果出来,自定义view学习一般是这样的吧,至少个人是这么认为的.
构造函数:
public Region() { this(nativeConstructor()); } /** Return a copy of the specified region */ public Region(Region region) { this(nativeConstructor()); nativeSetRegion(mNativeRegion, region.mNativeRegion); } /** Return a region set to the specified rectangle */ public Region(Rect r) { mNativeRegion = nativeConstructor(); nativeSetRect(mNativeRegion, r.left, r.top, r.right, r.bottom); } /** Return a region set to the specified rectangle */ public Region(int left, int top, int right, int bottom) { mNativeRegion = nativeConstructor(); nativeSetRect(mNativeRegion, left, top, right, bottom); }我们发现有四个构造函数,先每个函数试试什么意思,
package com.simple; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Region; import android.graphics.RegionIterator; import android.util.AttributeSet; import android.view.View; /** * Created by admin on 2017/7/11. */ public class RegionView extends View { private Paint mPaint; public RegionView(Context context) { this(context,null); } public RegionView(Context context, AttributeSet attrs) { this(context, attrs,0); } public RegionView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initPaint(); } private void initPaint() { mPaint = new Paint(); mPaint.setColor(Color.GREEN); mPaint.setStrokeWidth(3); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Region region = new Region(); drawRegion(canvas,region,mPaint); } private void drawRegion(Canvas canvas,Region rgn,Paint paint) { RegionIterator iter = new RegionIterator(rgn); Rect r = new Rect(); while (iter.next(r)) { canvas.drawRect(r, paint); } } }上面是使用空的构造函数创建Region对象,如图:
用崔健的一首歌来形容是一无所有啊,对,没错,确实是什么都没有,因为空的构造函数是没指定区域的,哪它就相当于是(0,0)坐标位置了.
现在构造函数改变一下:
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Region region = new Region(0,0,100,100); drawRegion(canvas,region,mPaint); } private void drawRegion(Canvas canvas,Region rgn,Paint paint) { RegionIterator iter = new RegionIterator(rgn); Rect r = new Rect(); while (iter.next(r)) { canvas.drawRect(r, paint); } }效果图:
这是使用一个矩形构造了一个区域,这和 public Region(Rect r)构造函数是一样的,Rect只是把四个变量封装了一下而已,
现在就剩下最后一个构造函数没说了:
public Region(Region region) { this(nativeConstructor()); nativeSetRegion(mNativeRegion, region.mNativeRegion); }关于一个构造函数中传递的是它自己本身的话,一般是copy里面值,比如Rect构造函数中传递一个Rect,无法是把构造函数中的Rect中的left,top,right,bottom赋值给当前要构造的对象Rect而已.
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Region region1 = new Region(