Android: how to programmatically round only top corners of a bitmap?

后端 未结 1 680
半阙折子戏
半阙折子戏 2021-02-09 15:05

I\'m currently using this code:

@Override
public Bitmap transform(Bitmap source) {
    Bitmap result = Bitmap.createBitmap(source.getWidth(), source.getHeight()         


        
相关标签:
1条回答
  • 2021-02-09 15:47

    Here is your answer: https://stackoverflow.com/a/5252726/1969801

    public static Bitmap getRoundedCornerBitmap(Context context, Bitmap input, int pixels , int w , int h , boolean squareTL, boolean squareTR, boolean squareBL, boolean squareBR  ) {
    
    Bitmap output = Bitmap.createBitmap(w, h, Config.ARGB_8888);
    Canvas canvas = new Canvas(output);
    final float densityMultiplier = context.getResources().getDisplayMetrics().density;
    
    final int color = 0xff424242;
    final Paint paint = new Paint();
    final Rect rect = new Rect(0, 0, w, h);
    final RectF rectF = new RectF(rect);
    
    //make sure that our rounded corner is scaled appropriately
    final float roundPx = pixels*densityMultiplier;
    
    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(color);
    canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
    
    
    //draw rectangles over the corners we want to be square
    if (squareTL ){
        canvas.drawRect(0, 0, w/2, h/2, paint);
    }
    if (squareTR ){
        canvas.drawRect(w/2, 0, w, h/2, paint);
    }
    if (squareBL ){
        canvas.drawRect(0, h/2, w/2, h, paint);
    }
    if (squareBR ){
        canvas.drawRect(w/2, h/2, w, h, paint);
    }
    
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(input, 0,0, paint);
    
    return output;
     }
    

    And the onDraw function:

     @Override
     protected void onDraw(Canvas canvas) {
    //super.onDraw(canvas);
        Drawable drawable = getDrawable();
    
        Bitmap b =  ((BitmapDrawable)drawable).getBitmap() ;
        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);
    
        int w = getWidth(), h = getHeight();
    
    
        Bitmap roundBitmap =  CropImageView.getRoundedCornerBitmap( getContext(), bitmap,10 , w, h , true, false,true, false);
        canvas.drawBitmap(roundBitmap, 0,0 , null);
    }
    
    0 讨论(0)
提交回复
热议问题