自定义imageView使用遮罩实现

来源:互联网 发布:吉林大学网络课程中心 编辑:程序博客网 时间:2024/05/29 12:39


package com.example.mask;


import android.widget.ImageView;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;
public class MaskImage extends ImageView{
        private static final String TAG = "MaskImage";
int mImageSource=0;
        int mMaskSource=0; 
        RuntimeException mException;


        public MaskImage(Context context, AttributeSet attrs) {
                super(context, attrs);
                TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.MaskImage, 0, 0);
                mImageSource = typedArray.getResourceId(R.styleable.MaskImage_image, 0);
                mMaskSource = typedArray.getResourceId(R.styleable.MaskImage_mask, 0);


                if (mImageSource == 0 || mMaskSource == 0) {
                        mException = new IllegalArgumentException(typedArray.getPositionDescription() + 
                                        ": The content attribute is required and must refer to a valid image.");
                }


                if (mException != null) 
                        throw mException;
       /**
        * 主要代码实现
        */
                //获取图片的资源文件
                Bitmap original = BitmapFactory.decodeResource(getResources(), mImageSource);
                
                //获取遮罩层图片
                Bitmap maskRes = BitmapFactory.decodeResource(getResources(), mMaskSource);
//                Options opts=new Options();
//                opts.inJustDecodeBounds=true;
// Bitmap maskRess = BitmapFactory.decodeResource(getResources(), mMaskSource,opts);
// float scare=1;
// int height=opts.outHeight;
// int width=opts.outWidth;
// float scareX=original.getWidth()/width;
// float scareY=original.getHeight()/height;
// scare=scareX>=scareY?scareX:scareY;
// opts.inSampleSize=(int) scare+1;
// opts.inJustDecodeBounds=false;
// Bitmap mask = BitmapFactory.decodeResource(getResources(), mMaskSource,opts);
                int width=maskRes.getWidth();
                int height=maskRes.getHeight();
                int newWidth=original.getWidth();
                int newHight=original.getHeight();
Matrix m=new Matrix();
m.postScale((float)newWidth/width, (float)newHight/height);
Bitmap mask = Bitmap.createBitmap(maskRes, 0, 0, width, height, m, false);
                

 
                Bitmap result = Bitmap.createBitmap(mask.getWidth(), mask.getHeight(), Config.ARGB_8888);
                
             //将遮罩层的图片放到画布中
                Canvas mCanvas = new Canvas(result);
                Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
                
                //设置两张图片相交时的模式 
                paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
                mCanvas.drawBitmap(original, 0, 0, null);
                mCanvas.drawBitmap(mask, 0, 0, paint);
                paint.setXfermode(null);
                setImageBitmap(result);
                setScaleType(ScaleType.FIT_XY); 
                
                typedArray.recycle();
        }


}


自定义属性

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MaskImage">
        <attr name="image" format="reference" />
        <attr name="mask" format="reference" />
    </declare-styleable>
</resources>

附常用工具转载

1、Drawable → Bitmap

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
publicstatic Bitmap drawableToBitmap(Drawable drawable) {
 
Bitmap bitmap = Bitmap
 
.createBitmap(
 
drawable.getIntrinsicWidth(),
 
drawable.getIntrinsicHeight(),
 
drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
 
: Bitmap.Config.RGB_565);
 
Canvas canvas = newCanvas(bitmap);
 
// canvas.setBitmap(bitmap);
 
drawable.setBounds(0,0, drawable.getIntrinsicWidth(),
 
drawable.getIntrinsicHeight());
 
drawable.draw(canvas);
 
returnbitmap;
 
}

2、从资源中获取Bitmap

?
1
2
3
Resources res=getResources();
 
Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.pic);
3、Bitmap → byte[]
?
1
2
3
4
5
6
7
8
9
privatebyte[] Bitmap2Bytes(Bitmap bm){
 
ByteArrayOutputStream baos = newByteArrayOutputStream();
 
bm.compress(Bitmap.CompressFormat.PNG,100, baos);
 
returnbaos.toByteArray();
 
}

4、byte[] → Bitmap

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
privateBitmap Bytes2Bimap(byte[] b){
 
if(b.length!=0){
 
returnBitmapFactory.decodeByteArray(b, 0, b.length);
 
}
 
else{
 
returnnull;
 
}
 
}
5、保存bitmap

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
staticboolean saveBitmap2file(Bitmap bmp,String filename){
 
CompressFormat format= Bitmap.CompressFormat.JPEG;
 
intquality = 100;
 
OutputStream stream = null;
 
try{
 
stream = newFileOutputStream("/sdcard/"+ filename);
 
}catch(FileNotFoundException e) {
 
// TODO Auto-generated catch block
 
Generated by Foxit PDF Creator © Foxit Software
 
http://www.foxitsoftware.com For evaluation only.
 
e.printStackTrace();
 
}
 
returnbmp.compress(format, quality, stream);
 
}

6、将图片按自己的要求缩放

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// 图片源
 
Bitmap bm = BitmapFactory.decodeStream(getResources()
 
.openRawResource(R.drawable.dog));
 
// 获得图片的宽高
 
intwidth = bm.getWidth();
 
intheight = bm.getHeight();
 
// 设置想要的大小
 
intnewWidth = 320;
 
intnewHeight = 480;
 
// 计算缩放比例
 
floatscaleWidth = ((float) newWidth) / width;
 
floatscaleHeight = ((float) newHeight) / height;
 
// 取得想要缩放的matrix参数
 
Matrix matrix = newMatrix();
 
matrix.postScale(scaleWidth, scaleHeight);
 
// 得到新的图片
 
Bitmap newbm = Bitmap.createBitmap(bm, 0,0, width, height, matrix,
 
true);
 
// 放在画布上
 
canvas.drawBitmap(newbm,0,0, paint);

7:File图片转Bitmap

?
1
Bitmap bt = BitmapFactory.decodeFile("/sdcard/myImage/"+ "head.jpg");//图片地址

8://图片转Bitmap

?
1
2
3
4
5
6
7
8
9
publicBitmap drawableToBitamp(intdrawableResource) {<span style="white-space:pre">    </span>//可以取raw里面的资源
        BitmapFactory.Options opt = newBitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        InputStream is = this.getResources().openRawResource(drawableResource);
        BitmapFactory.decodeStream(is,null, opt);
        returnBitmapFactory.decodeStream(is, null, opt);

0 0
原创粉丝点击