2023-07-17

public Bitmap getVerticalTransparentBitmap(Bitmap bitmap,int direction,float position,int containerWidth,int containerHeight,boolean isRound) {

if (bitmap.getWidth() ==0 || bitmap.getHeight() ==0) {

return bitmap;

}

Paint paint =new Paint();

int width = bitmap.getWidth();

int height = bitmap.getHeight();

float ratio = containerWidth / (float) containerHeight;

Bitmap targetBitmap = Bitmap.createBitmap(containerWidth, containerHeight, Bitmap.Config.ARGB_8888);

Canvas canvas =new Canvas(targetBitmap);

float bitmapRatio = width / (float) height;

Matrix matrix =new Matrix();

if (bitmapRatio > ratio) {

float scale = containerHeight / (float) height;

matrix.postScale(scale, scale);

float offset = (width * scale - containerWidth) /2;

Bitmap scaledBitmap = Bitmap.createBitmap(bitmap,0,0, width, height, matrix,true);

canvas.drawBitmap(scaledBitmap, -offset,0f, paint);

}else {

float scale = containerWidth / (float) width;

matrix.postScale(scale, scale);

float offset = (height * scale - containerHeight) /2;

Bitmap scaledBitmap = Bitmap.createBitmap(bitmap,0,0, width, height, matrix,true);

canvas.drawBitmap(scaledBitmap,0f, -offset, paint);

}

float p = direction ==0 ? position :1 - position;

int[] color = direction ==0 ?

new int[]{Color.parseColor("#00000000"), Color.parseColor("#FFFFFF")} :

new int[]{Color.parseColor("#FFFFFF"), Color.parseColor("#00000000")};

Bitmap shapeBottom = Bitmap.createBitmap(containerWidth, (int) (containerHeight * p), Bitmap.Config.ARGB_8888);

Canvas canvasBottom =new Canvas(shapeBottom);

GradientDrawable gradientDrawable =new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, color);

gradientDrawable.setBounds(0,0, canvasBottom.getWidth(), canvasBottom.getHeight());

gradientDrawable.draw(canvasBottom);

Paint overlayPaint =new Paint();

overlayPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.MULTIPLY));

float top = direction ==0 ?0f : containerHeight - shapeBottom.getHeight();

canvas.drawBitmap(shapeBottom,0f, top, overlayPaint);

return targetBitmap;

}

实现图片的底部渐变效果

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容