Android自定義ImageView:在圖片上添加一個圖層

LeoraAnders 8年前發布 | 20K 次閱讀 安卓開發 Android開發 移動開發

先看下效果圖:

01.jpg

這是兩張前后對比圖,右邊第二張圖里面的已搶光標簽圖片當已經沒有商品的時候就會顯示了,在每個圖片的中心位置,第一想法是在ImageView的外層再套一層RelativeLayout

<RelativeLayout    
  android:layout_width="match_parent" 
  android:layout_height="wrap_content"> 
<SelectableRoundedImageView        
  android:id="@+id/imageView"        
  style="@style/margin_distance"        
  android:layout_width="match_parent"        
  android:layout_height="0dp"        
  android:layout_weight="1"        
  android:background="@drawable/youxuan_bg_shape_normol"        
  android:contentDescription="@string/app_name"        
  android:padding="1dp"        
  android:scaleType="centerCrop" />    
<ImageView        
  android:id="@+id/iv_empty_pic"        
  android:layout_width="wrap_content"        
  android:layout_height="wrap_content"        
  android:layout_centerInParent="true" />
</RelativeLayout>

這樣當然是可以的,然而如果XML布局本身就很復雜,用這樣的寫法又給View Tree加了一層,不夠優雅,下面介紹另一種實現方式:自定義View

public class CenterImage extends ImageView {    
private Paint paint;    
private boolean isCenterImgShow;    
private Bitmap bitmap;    
public void setCenterImgShow(boolean centerImgShow) {        
   isCenterImgShow = centerImgShow;        
   if (isCenterImgShow) {            
   bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);            
   invalidate();        
   }   
 }    
 public CenterImage(Context context) {        
   super(context);        
   init();    
 }    
public CenterImage(Context context, AttributeSet attrs) {        
   super(context, attrs);        
   init();    
 }    
public CenterImage(Context context, AttributeSet attrs, int defStyleAttr) {        
    super(context, attrs, defStyleAttr);       
    init();   
 }    
private void init() {        
   paint = new Paint();   
 }    
@Override    
protected void onDraw(Canvas canvas) {       
  super.onDraw(canvas);       
  if (isCenterImgShow && bitmap != null) {            
  canvas.drawBitmap(bitmap, getMeasuredWidth() / 2 - bitmap.getWidth() / 2, getMeasuredHeight() / 2 - bitmap.getHeight() / 2, paint);       
  }   
 }
}

XML中:

<com.henanjianye.soon.communityo2o.view.CenterImage     
   android:id="@+id/goodsImage"     
   android:layout_width="match_parent"    
   android:layout_height="100dp"    
   android:layout_alignParentEnd="true"    
   android:layout_alignParentRight="true"    
   android:contentDescription="@string/app_name"    
   android:scaleType="centerCrop"    
   android:src="@mipmap/yijia_default_bg" />

代碼中拿到CenterImage的對象:

CenterImage mGoodsImg =(CenterImage)findViewById(R.id.GoodsImage);
mGoodsImg.setCenterImgShow(true);

當setCenterImgShow()里的invalidate()方法被調用后,CenterImage的onDraw()方法會重新被調用并重新繪制,這樣就可以愉快地在ImageView的上面新加一個圖層。

 

來自:http://www.jianshu.com/p/a3d9101b3c23

 

 本文由用戶 LeoraAnders 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!