Android 模仿微信发送图片 钟罩效果

时间:2015-02-10 18:35:47   收藏:0   阅读:284
参考资料http://trylovecatch.iteye.com/blog/1189452 http://bbs.51cto.com/thread-1031415-1.html### 1、添加资源文件:attrs.xml 复制内容到剪贴板 代码: 2、创建自定义组件MaskImage.java 复制内容到剪贴板 代码: package com.xzw.mask.widget; 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.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.util.AttributeSet; import android.widget.ImageView; import com.xzw.mask.R; public class MaskImage extends ImageView{ 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 mask = BitmapFactory.decodeResource(getResources(), mMaskSource); 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.CENTER); typedArray.recycle(); } } 3、在布局文件中添加 复制内容到剪贴板 代码: 这里要记得添加namespace也就是xml的命名空间 复制内容到剪贴板 代码: xmlns:maskimage="http://schemas.android.com/apk/res/com.xzw.mask" xmlns:maskimage的自我们自定义的命名空间方式。 命名规则是: http://schemas.android.com/apk/res/包名 这样代码就实现了遮罩效果了。说了这么多什么是遮罩还没说呢?就是有两张图片,一张图片放在另外一张图片的上面,放在上面的图片叫做遮罩层,下面的叫做被遮罩层,两张图片重叠的部分会显示出来,就形成了遮罩的效果。遮罩用在哪里了,就比如说头像,头像原来是正方形,突然想变成圆形的,这样搞就很简单的实现了。 嘿嘿希望这个功能对大家有帮助哈。 源码: mask.zip (1.06 MB) 参考: http://stackoverflow.com/questions/12614542/maskingcrop-image-in-frame http://lipeng88213.iteye.com/blog/1189452
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!