public class SquareImageView extends View { private Paint mPaint; private Bitmap bitmap; int left; int top; //这个构造方法,是new对象,实例化对象的时候调用的, /* public SquareImageView(Context context) { super(context); mPaint=new Paint(); }*/ //这个构造方法,是在你的xml文件中调用的方法,就是在xml文件里写上全类名,当作组件用 public SquareImageView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); mPaint=new Paint(); bitmap= BitmapFactory.decodeFile("/storage/sdcard0/BIG-BANNER-YYSYHF.jpg"); //获取自定义属性数组 TypedArray array = context.getTheme().obtainStyledAttributes(attrs,R.styleable.SquareImageView,0,0); //获取具体的自定义属性 int color=array.getColor(R.styleable.SquareImageView_paintColor,0x000000); //获取具体的自定义属性 left= array.getInteger(R.styleable.SquareImageView_left,100); //使用xml里自定义属性的值 mPaint.setColor(color); } public SquareImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public SquareImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } //view的绘制流程,分为onMeasure(测量获得组件的尺寸,提供给onLayout使用,onLayout还不一定使用) //onLayout 布局,知道设置组件的位置 // ondraw()把组件画出来 @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawBitmap(drawSquare(left),0,0,mPaint); } public Bitmap drawSquare(int left){ Paint paint=new Paint(); paint.setColor(Color.YELLOW); Rect rect=new Rect(left,50,0,0); Bitmap bm=Bitmap.createBitmap(bitmap.getWidth(),bitmap.getHeight().Config.ARGB_8888); Canvas canvas=new Canvas(bm); // canvas.drawRect(rect,paint); canvas.drawBitmap(bitmap,0,0,paint); return bm; }
//在res/values/attrs.xml里添加 <declare-styleable name="SquareImageView"> <attr name="left" format="integer"/> <attr name="paintColor" format="color"/> </declare-styleable>
//定义一个命名控件 xmlns:app="http://schemas.android.com/apk/res-auto" //使用自定义view <com.example.*****.view.SquareImageView android:id="@+id/freeview" app:left="150" //使用属性 app:paintColor="@color/colorPrimaryDark" //使用属性 android:layout_width="match_parent" android:layout_height="300dp"> </com.example.*****.view.SquareImageView>
}