本文實例講述了Android開發使用Drawable繪制圓角與圓形圖案功能。分享給大家供大家參考,具體如下:
1. 創建類RoundCircleDrawable繼承Drawable
/** * 圓角矩形 * @Project App_View * @Package com.android.view.drawable * @author chenlin * @version 1.0 * @Date 2016年4月21日 * @Note TODO */public class RoundCircleDrawable extends Drawable{ private Paint mPaint;//畫筆 private int mWidth;//圖片寬與長度的最小值 private int mRadius;//半徑 private int mRound;//圓角 private RectF mRectF;//矩形 private Bitmap mBitmap;//圖片 private Type mType = Type.TYPE_ROUND;//默認是矩形 //設置類型 enum Type{ TYPE_ROUND, TYPE_CICLE; } public RoundCircleDrawable(Bitmap bitmap){ this.mBitmap = bitmap; //初始化畫筆 mPaint = new Paint(); mPaint.setAntiAlias(true); BitmapShader shader = new BitmapShader(mBitmap, TileMode.CLAMP, TileMode.CLAMP); mPaint.setShader(shader); mWidth = Math.min(mBitmap.getWidth(), mBitmap.getHeight()); mRadius = mWidth / 2; } /** * 向外提供設置圖片類型的方法 * @param type */ public void setType(Type type){ this.mType = type; } /** * 暴露給外面設置圓角的大小 * * @param round */ public void setRound(int round) { this.mRound = round; } @Override public void setBounds(int left, int top, int right, int bottom) { super.setBounds(left, top, right, bottom); mRectF = new RectF(left, top, right, bottom); } @Override public void draw(Canvas canvas) { if (mType == Type.TYPE_ROUND) { canvas.drawRoundRect(mRectF, mRound, mRound, mPaint); }else { canvas.drawCircle(mWidth / 2, mWidth / 2, mRadius, mPaint); } } @Override public int getIntrinsicWidth() { if (mType == Type.TYPE_CICLE) { return mWidth; }else { return mBitmap.getWidth(); } } @Override public int getIntrinsicHeight() { if (mType == Type.TYPE_CICLE) { return mWidth; }else { return mBitmap.getHeight(); } } @Override public void setAlpha(int alpha) { mPaint.setAlpha(alpha); } @Override public void setColorFilter(ColorFilter cf) { mPaint.setColorFilter(cf); } @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; }}2. 實現方法
public class RoundActivity extends Activity { private ImageView mImageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_round_drawable); mImageView = (ImageView) findViewById(R.id.iv_round); Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.aa); //RoundImageDrawable drawable = new RoundImageDrawable(bitmap); //drawable.setRound(30); RoundCircleDrawable drawable = new RoundCircleDrawable(bitmap); drawable.setRound(50); mImageView.setImageDrawable(drawable); }}更多關于Android相關內容感興趣的讀者可查看本站專題:《Android圖形與圖像處理技巧總結》、《Android開發入門與進階教程》、《Android調試技巧與常見問題解決方法匯總》、《Android基本組件用法總結》、《Android視圖View技巧總結》、《Android布局layout技巧總結》及《Android控件用法總結》
希望本文所述對大家Android程序設計有所幫助。
新聞熱點
疑難解答