本文实例讲述了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程序设计有所帮助。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。