1. 程式人生 > >ImageView設計成圓角的形狀

ImageView設計成圓角的形狀

今天在做程式的時候遇到一個問題,是把圖片顯示成圓角的,我們平時所寫的ImageView都是直角的,看起來是很生硬的。如果把四個角給設計成圓角,看起來就會圓潤一些,沒有那麼生硬。這個問題想了很久,也想過很多方法,找了很久,後來想到直接在ImageView.onDraw的時候,給他畫出圓角來,這樣,這個ImageView裡面的ImageBitmap就也有圓角的效果了。實現的程式碼如下:

新建一個class類

  1. public class RoundCornerImageView extends ImageView {
  2. public RoundCornerImageView(Context context) {
  3. super(context);
  4. }
  5. public RoundCornerImageView(Context context, AttributeSet attrs) {
  6. super(context, attrs);
  7. }
  8. public RoundCornerImageView(Context context, AttributeSet attrs,
  9. int defStyle) {
  10. super(context, attrs, defStyle);
  11. }
  12. @Override
  13. protected void onDraw(Canvas canvas) {
  14. Path clipPath = new Path();
  15. int w = this.getWidth();
  16. int h = this.getHeight();
  17. clipPath.addRoundRect(new RectF(0, 0, w, h), 10.0f, 10.0f, Path.Direction.CW);
  18. canvas.clipPath(clipPath);
  19. super.onDraw(canvas);
  20. }
  21. }

下面這行程式碼就能畫出圓角效果,10度的角

[java] view plaincopyprint?
  1. clipPath.addRoundRect(new RectF(0, 0, w, h), 10.0f, 10.0f, Path.Direction.CW);

在layout.xml中直接使用RoundCornerImageView就會出現圓角的ImageView效果

[html] view plaincopyprint?
  1. <com.qise.app.ui.utils.RoundCornerImageView android:id="@+id/foodItem_foodImg"
  2. android:src="@drawable/food_img_na"
  3. android:layout_width="80dip"
  4. android:layout_height="80dip"
  5. android:scaleType="centerCrop"
  6. />

有什麼不足之處還望各位大神多多指教,大家如果有什麼更好的方法可以一起來研究。

http://blog.csdn.net/u013184970/article/details/51911757