如何在Android中利用Drawable绘制一个圆角
如何在Android中利用Drawable绘制一个圆角?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
创新互联公司2013年成立,是专业互联网技术服务公司,拥有项目成都网站设计、做网站网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元吉水做网站,已为上家服务,为吉水各地企业和个人服务,联系电话:13518219792
1. 创建类RoundCircleDrawable继承Drawable
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中利用Drawable绘制一个圆角的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!
本文题目:如何在Android中利用Drawable绘制一个圆角
文章网址:http://myzitong.com/article/jioipi.html