2017-09-25 86 views
0

我试图画一个位图到画布。它导致拉伸位图。我想要的是如果图像很小,不要拉伸,如果图像比显示更大,则裁剪图像。这是如何实现的。android:绘制到画布没有拉伸

我具有延伸DrawableWrapper

public class MyDrawable extends DrawableWrapper { 
public MyDrawable(Drawable drawable) { 
     super(drawable); 


    } 
    public MyDrawable(final Context context, Bitmap bitmap) { 
     this(new BitmapDrawable(context.getResources(),bitmap)); 
} 

我具有boundsChnage()此代码

protected void onBoundsChange(Rect bounds) { 
    mBitmap = Bitmap.createBitmap(bounds.width(), bounds.height(), Bitmap.Config.ARGB_8888); 
      Canvas canvas = new Canvas(mBitmap); 
      super.draw(canvas); 
} 

这导致绘制可绘制拉伸的裁剪部分的自定义绘制。

回答

0
i think it will help you. 

Bitmap scaleBitmap = scaleBitmap(bitmap); 
RectF rectF = new RectF(0, (mHeight scaleBitmap.getHeight()), 
scaleBitmap.getWidth(), scaleBitmap.getHeight()); 
canvas.drawBitmap(scaleBitmap, null, rectF, null); 

private Bitmap scaleBitmap(Bitmap bm) { 
     int width = bm.getWidth(); 
     int height = bm.getHeight(); 

     Log.v("Pictures", "Width and height are " + width + "--" + height); 
     int mWidth = this.getResources().getDisplayMetrics().widthPixels; 
     int mHeight = this.getResources().getDisplayMetrics().heightPixels; 
     if (width > height) { 
      // landscape 
      int ratio = width/mWidth; 
      width = mWidth; 
      height = height/ratio; 
     } else if (height > width) { 
      // portrait 
      int ratio = height/mHeight; 
      height = mHeight; 
      width = width/ratio; 
     } else { 
      // square 
      height = mWidth; 
      width = mWidth; 
     } 

     Log.v("Pictures", "after scaling Width and height are " + width + "--" + height); 

     bm = Bitmap.createScaledBitmap(bm, width, height, true); 
     return bm; 
    }