您的位置:首页 > 移动开发 > Android开发

[带效果图]圆角矩形图片自定义控件

2016-12-05 18:59 162 查看
效果图:



常用的属性类型:

属性类型名称属性类型
color颜色
boolean布尔类型
string文本类型
folat小数
dimension尺寸类型(如100dp)
reference引用类型(如@String)
reference|color引用或者颜色
使用方法:

<com.yt.utils.RoundRectImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:chamfer="2" />


values/attrs:

<declare-styleable name="RoundRectImageView">
<attr name="chamfer" format="integer" />
</declare-styleable>


代码:

package com.yt.utils;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.miu.apps.miss.R;

/**
* yt
* Created by Administrator on 2016/12/5.
* 圆角图片 的自定义控件
*/
public class RoundRectImageView extends ImageView {
private Paint paint;
private int chamfer;

public RoundRectImageView(Context context) {
this(context,null);
}

public RoundRectImageView(Context context, AttributeSet attrs) {
this(context, attrs,0);
}

public RoundRectImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);

TypedArray typedArray = context.obtainStyledAttributes(attrs,
R.styleable.RoundRectImageView);
chamfer = typedArray.getInteger(R.styleable.RoundRectImageView_chamfer, 0);   //获取倒角幅度

paint  = new Paint();
}

/**
* 绘制圆角矩形图片
*/
@Override
protected void onDraw(Canvas canvas) {

Drawable drawable = getDrawable();
if (null != drawable) {
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
Bitmap b = getRoundBitmap(bitmap, chamfer);
final Rect rectSrc = new Rect(0, 0, b.getWidth(), b.getHeight());
final Rect rectDest = new Rect(0,0,getWidth(),getHeight());
paint.reset();
canvas.drawBitmap(b, rectSrc, rectDest, paint);

} else {
super.onDraw(canvas);
}
}

/**
* 获取圆角矩形图片方法
* @param bitmap
* @param roundPx  倒角幅度
* @return Bitmap
*/
private Bitmap getRoundBitmap(Bitmap bitmap, int roundPx) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);

final int color = 0xff424242;

final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
int x = bitmap.getWidth();

canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
pa
4000
int.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐