Android 图像处理(类型转换,比例缩放,倒影,圆角)的小例子
程序员文章站
2023-12-04 21:18:40
1.放大缩小图片
复制代码 代码如下:public static bitmap zoombitmap(bitmap bitmap,int w,int h){ &...
1.放大缩小图片
复制代码 代码如下:
public static bitmap zoombitmap(bitmap bitmap,int w,int h){
int width = bitmap.getwidth();
int height = bitmap.getheight();
matrix matrix = new matrix();
float scalewidht = ((float)w / width);
float scaleheight = ((float)h / height);
matrix.postscale(scalewidht, scaleheight);
bitmap newbmp = bitmap.createbitmap(bitmap, 0, 0, width, height, matrix, true);
return newbmp;
}
2.获得圆角图片的方法
复制代码 代码如下:
public static bitmap getroundedcornerbitmap(bitmap bitmap,float roundpx){
bitmap output = bitmap.createbitmap(bitmap.getwidth(), bitmap.getheight(), config.argb_8888);
canvas canvas = new canvas(output);
final int color = 0xff424242;
final paint paint = new paint();
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);
canvas.drawroundrect(rectf, roundpx, roundpx, paint);
paint.setxfermode(new porterduffxfermode(mode.src_in));
canvas.drawbitmap(bitmap, rect, rect, paint);
return output;
}
3.获得带倒影的图片方法
复制代码 代码如下:
public static bitmap createreflectionimagewithorigin(bitmap bitmap){
final int reflectiongap = 4;
int width = bitmap.getwidth();
int height = bitmap.getheight();
matrix matrix = new matrix();
matrix.prescale(1, -1);
bitmap reflectionimage = bitmap.createbitmap(bitmap,0, height/2, width, height/2, matrix, false);
bitmap bitmapwithreflection = bitmap.createbitmap(width, (height + height/2), config.argb_8888);
canvas canvas = new canvas(bitmapwithreflection);
canvas.drawbitmap(bitmap, 0, 0, null);
paint deafalutpaint = new paint();
canvas.drawrect(0, height,width,height + reflectiongap, deafalutpaint);
canvas.drawbitmap(reflectionimage, 0, height + reflectiongap, null);
paint paint = new paint();
lineargradient shader = new lineargradient(0, bitmap.getheight(), 0,
bitmapwithreflection.getheight() + reflectiongap, 0x70ffffff, 0x00ffffff, tilemode.clamp);
paint.setshader(shader);
// set the transfer mode to be porter duff and destination in
paint.setxfermode(new porterduffxfermode(mode.dst_in));
// draw a rectangle using the paint with our linear gradient
canvas.drawrect(0, height, width, bitmapwithreflection.getheight()
+ reflectiongap, paint);
return bitmapwithreflection;
}
4.将drawable转化为bitmap
复制代码 代码如下:
public static bitmap drawabletobitmap(drawable drawable){
int width = drawable.getintrinsicwidth();
int height = drawable.getintrinsicheight();
bitmap bitmap = bitmap.createbitmap(width, height,
drawable.getopacity() != pixelformat.opaque ? bitmap.config.argb_8888: bitmap.config.rgb_565);
canvas canvas = new canvas(bitmap);
drawable.setbounds(0,0,width,height);
drawable.draw(canvas);
return bitmap;
}