自定义控件的用法

来源:互联网 发布:黑魂女性捏脸数据 编辑:程序博客网 时间:2024/04/28 08:54

 效果图:圆角头像就是个自定义控件,它是个继承自ImageView的类,使用方法是在xml里写完整的包名,类名


<LinearLayout

                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:gravity="center"
                android:orientation="horizontal" >


                <com.handaer.hbdpurse.widget.RoundImageView
                    android:id="@+id/iv_info_icon"
                    android:layout_width="100dp"
                    android:layout_height="100dp"
                    android:background="@drawable/user_head_bg"
                    android:scaleType="centerInside"
                    android:src="@drawable/default_head_icon" />


                <TextView
                    android:id="@+id/tv_info_phone"
                    style="@style/shadow_text"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="15dp"
                    android:textColor="#ffffff"
                    android:textSize="26sp" />

            </LinearLayout>

public class RoundImageView extends ImageView {
//构造方法重载方法一
public RoundImageView(Context context) {
this(context, null, 0);
}
//构造方法重载方法二
public RoundImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
//构造方法重载方法三
public RoundImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
getRoundedCornerBitmap(((BitmapDrawable) getDrawable()).getBitmap());
}
//设置一个位图作为这个ImageView内容。
@Override
public void setImageBitmap(Bitmap bm) {
getRoundedCornerBitmap(bm);//获得圆角图片的方法
}


private void setImageBitmap(Bitmap bm, boolean isRound) {
if (isRound) {
super.setImageBitmap(bm);
}
}
//设置一个drawable作为这个ImageView内容。
@Override
public void setImageResource(int resId) {


Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(),
resId);
getRoundedCornerBitmap(originalBitmap);
}


/**
* 获得圆角图片的方法

* @param bitmap
* @param roundPx
* @return
*/
private void getRoundedCornerBitmap(Bitmap bitmap) {
//获得宽高
int w = bitmap.getWidth();
int h = bitmap.getHeight();
int size = Math.min(w, h);
Bitmap output = Bitmap
.createBitmap(size, size, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
Paint paint = new Paint(1);
paint.setColor(0xfff6f6f6);
RectF rectf = new RectF(0F, 0F, size, size);
canvas.drawOval(rectf, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_ATOP));
canvas.drawBitmap(bitmap, 0, 0, paint);
this.setImageBitmap(output, true);
}
}

0 0
原创粉丝点击