Android自訂View基礎

來源:互聯網
上載者:User

這個就一個簡單的自訂View控間,  在xml中註冊即可顯示  看個把。

import android.content.Context;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.graphics.Paint.Align;import android.graphics.Paint.Style;import android.util.AttributeSet;import android.view.View;public class DiyView extends View{public DiyView(Context context){super(context);// TODO Auto-generated constructor stub}public DiyView(Context context, AttributeSet attrs){super(context, attrs);}@Overrideprotected void onDraw(Canvas canvas){super.onDraw(canvas);//定義畫筆Paint paint=new Paint(); //設定其屬性paint.setStrokeJoin(Paint.Join.ROUND);paint.setStrokeCap(Paint.Cap.ROUND);paint.setColor(Color.RED);//畫線canvas.drawLine(0, 0, 300, 0, paint);paint.setColor(Color.GREEN);paint.setStyle(Style.STROKE);//畫圓canvas.drawCircle(20, 80, 20, paint);paint.setStyle(Style.FILL);paint.setColor(Color.BLUE);//矩形canvas.drawRect(0, 200, 50, 300, paint);paint.setColor(Color.GRAY);paint.setTextSize(20);paint.setTextAlign(Align.CENTER);//文字canvas.drawText("test", 150, 150, paint);//圖片Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);canvas.drawBitmap(bitmap, 300, 300, paint);paint.setColor(Color.BLACK);paint.setStrokeWidth(40);//畫點 ,這裡看起來像個圓, 主要是設定setStrokeWidth所以才比較大int colorfuls[]=new int[]{Color.BLUE,Color.GREEN,Color.RED,Color.MAGENTA,Color.BLACK};for(int i =0;i<200;i+=40){paint.setColor( colorfuls[i/40]);canvas.drawPoint(200, 200+i, paint);}canvas.save();}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.