Android 自定義view淺析
阿新 • • 發佈:2018-11-14
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>
}