ImageView設計成圓角的形狀
阿新 • • 發佈:2019-01-04
今天在做程式的時候遇到一個問題,是把圖片顯示成圓角的,我們平時所寫的ImageView都是直角的,看起來是很生硬的。如果把四個角給設計成圓角,看起來就會圓潤一些,沒有那麼生硬。這個問題想了很久,也想過很多方法,找了很久,後來想到直接在ImageView.onDraw的時候,給他畫出圓角來,這樣,這個ImageView裡面的ImageBitmap就也有圓角的效果了。實現的程式碼如下:
新建一個class類
- public class RoundCornerImageView extends ImageView {
-
public RoundCornerImageView(Context context) {
- super(context);
- }
- public RoundCornerImageView(Context context, AttributeSet attrs) {
- super(context, attrs);
- }
- public RoundCornerImageView(Context context, AttributeSet attrs,
- int defStyle) {
- super(context, attrs, defStyle);
- }
- @Override
- protected void onDraw(Canvas canvas) {
-
Path clipPath = new Path();
- int w = this.getWidth();
- int h = this.getHeight();
- clipPath.addRoundRect(new RectF(0, 0, w, h), 10.0f, 10.0f, Path.Direction.CW);
- canvas.clipPath(clipPath);
- super.onDraw(canvas);
- }
- }
下面這行程式碼就能畫出圓角效果,10度的角
[java] view plaincopyprint?-
clipPath.addRoundRect(new RectF(0, 0,
w, h), 10.0f, 10.0f, Path.Direction.CW);
在layout.xml中直接使用RoundCornerImageView就會出現圓角的ImageView效果
[html] view plaincopyprint?- <com.qise.app.ui.utils.RoundCornerImageView android:id="@+id/foodItem_foodImg"
- android:src="@drawable/food_img_na"
- android:layout_width="80dip"
- android:layout_height="80dip"
- android:scaleType="centerCrop"
- />
有什麼不足之處還望各位大神多多指教,大家如果有什麼更好的方法可以一起來研究。
http://blog.csdn.net/u013184970/article/details/51911757