Android Canvas和Bitmap結合繪圖詳解流程

Rect/RectF

存儲四個值的矩形類:左側、頂部、右側和底部。可用於直接在畫佈上繪制或僅用於存儲要繪制的對象的大小。Rect和RectF類之間的區別在於 RectF 存儲浮點值,而Rect類存儲整數。

private static Bitmap createDrawableBitmap(Drawable drawable) {
    int width = drawable.getIntrinsicWidth();
    int height = drawable.getIntrinsicHeight();
    if (width <= 0 || height <= 0) {
        return null;
    }
    float scale = Math.min(1.0f, ((float) MAX_IMAGE_SIZE) / ((float) (width * height)));
    if ((drawable instanceof BitmapDrawable) && scale == 1.0f) {
        return ((BitmapDrawable) drawable).getBitmap();
    }
    int bitmapWidth = (int) (((float) width) * scale);
    int bitmapHeight = (int) (((float) height) * scale);
    Bitmap bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    Rect existingBounds = drawable.getBounds();
    int left = existingBounds.left;
    int top = existingBounds.top;
    int right = existingBounds.right;
    int bottom = existingBounds.bottom;
    drawable.setBounds(0, 0, bitmapWidth, bitmapHeight);
    drawable.draw(canvas);
    drawable.setBounds(left, top, right, bottom);
    return bitmap;
}

Matrix

一個3 x 3的矩陣,用於存儲可用於轉換畫佈的信息。矩陣可以存儲以下類型的變換信息:縮放、傾斜、旋轉、平移。而每種變換方式都對應著三種方法:set方法將用新值替換當前的Matrix,不管之前Matrix的值是什麼。pre和post 方法將在當前Matrix包含的任何內容之前或之後應用新的轉換。

Matrix m = new Matrix();
m.setRotate(90);
m.setScale(3f,1f);
m.setTranslate(200, 200);

隻有平移,旋轉值和縮放值被重置

Matrix m = new Matrix();
m.preScale(3f,1f);
m.preTranslate(200f, 100f);
m.postScale(0.5f, 1f);
m.postTranslate(100f, 0f);

先進行平移(200f, 100f),然後進行縮放(3f, 1f),然後進行縮放(0.5f, 1f),最後進行平移(100f, 0f)

Matrix m = new Matrix();
m.postTranslate(200f, 0f);
m.preScale(0.5f, 1f);
m.setScale(1f, 1f);
m.postScale(5f, 1f);
m.preTranslate(200f, 100f);

先進行平移(200f, 100f),然後進行縮放(1f, 1f),最後進行縮放(5f, 1f)。因為用瞭set方法所以平移(200f, 0f)和縮放(0.5f, 1f)被覆蓋,不起作用

假如先進行平移(x, y),再進行縮放(sx, sy),那麼看到的平移效果等同於(x*sx, y*sy),因為縮放是將整個畫佈或者坐標系進行縮放的

Canvas

Canvas相當於Android的畫佈,可以把畫佈想象成一塊內存空間,也就是一個Bitmap。Canvas的API提供一整套在這個Bitmap上進行繪圖的操作方法。

  • drawBitmap(Bitmap bitmap, Matrix matrix, Paint paint)

使用指定的矩陣繪制位圖,繪制的時候會使用矩陣進行變換,矩陣和畫筆可以傳入空值

  • drawBitmap (Bitmap bitmap, Rect src, Rect dst, Paint paint)

將傳入的源圖bitmap指定的矩形區域src繪制到目標矩形區域dst中,如果矩形區域src傳入空值,則表示繪制整個源圖到目標矩形區域dst中,繪制的時候源圖或子集自動縮放/平移以填充目標矩形。如果繪制對應的畫筆通過方法setMaskFilter指定瞭超出原始位圖寬/高的掩碼過濾器(如BlurMaskFilter),則會位圖將繼續被繪制,就像在具有CLAMP模式的著色器中一樣。因此,原始寬/高之外的顏色將是復制的邊緣顏色。因為源矩形區域src對應的坐標空間是相對於源圖的,而目標矩形區域dst對應的坐標空間是繪制視圖對應的坐標空間,因此要控制好對應的縮放因子。

  • drawBitmap (Bitmap bitmap, Rect src, RectF dst, Paint paint)

矩陣示例:

Bitmap background = Bitmap.createBitmap((int)width, (int)height, Config.ARGB_8888);
float originalWidth = originalImage.getWidth(); 
float originalHeight = originalImage.getHeight();

Canvas canvas = new Canvas(background);

float scale = width / originalWidth;

float xTranslation = 0.0f;
float yTranslation = (height - originalHeight * scale) / 2.0f;

Matrix transformation = new Matrix();
transformation.postTranslate(xTranslation, yTranslation);
transformation.preScale(scale, scale);

Paint paint = new Paint();
paint.setFilterBitmap(true);

canvas.drawBitmap(originalImage, transformation, paint);

矩形區域示例:

public Bitmap cropCircle(Bitmap bitmap) {
  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());
  paint.setAntiAlias(true);
  canvas.drawARGB(0, 0, 0, 0);
  paint.setColor(color);
  canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2,
      bitmap.getWidth()/2, paint);
  paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
  canvas.drawBitmap(bitmap, rect, rect, paint);
  return output;
}

Bitmap

位圖,點陣圖,可以理解為int[] buffer,用來存儲每個像素點的容器。

  • Bitmap.createBitmap(int width, int height, Bitmap.Config config)
  • Bitmap.createBitmap(Bitmap src)
  • Bitmap.createBitmap(Bitmap source, int x, int y, int width, int height)
  • Bitmap.createBitmap(Bitmap source, int x, int y, int width, int height,Matrix m, boolean filter)
  • BitmapFactory.decodeByteArray(byte[] data, int offset, int length, BitmapFactory.Options opts)
  • BitmapFactory.decodeFile(String pathName, Options opts)
  • BitmapFactory.decodeStream(InputStream is, Rect outPadding,Options opts)

createBitmap生成示例:

public Bitmap transform(Bitmap source) {
  int size = Math.min(source.getWidth(), source.getHeight());
  int x = (source.getWidth() - size) / 2;
  int y = (source.getHeight() - size) / 2;
  Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size);
  if (squaredBitmap != source) {
    source.recycle();
  }
  Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());
  Canvas canvas = new Canvas(bitmap);
  Paint avatarPaint = new Paint();
  BitmapShader shader = new BitmapShader(squaredBitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
  avatarPaint.setShader(shader);
  Paint outlinePaint = new Paint();
  outlinePaint.setColor(Color.WHITE);
  outlinePaint.setStyle(Paint.Style.STROKE);
  outlinePaint.setStrokeWidth(STROKE_WIDTH);
  outlinePaint.setAntiAlias(true);
  float r = size / 2f;
  canvas.drawCircle(r, r, r, avatarPaint);
  canvas.drawCircle(r, r, r - STROKE_WIDTH / 2, outlinePaint);
  squaredBitmap.recycle();
  return bitmap;
}

BitmapFactory生成示例:

private static Bitmap decodeSampledBitmapFromUrl(String url, int reqWidth, int reqHeight) throws IOException {

	    // First decode with inJustDecodeBounds=true to check dimensions
	    final Options options = new Options();
	    options.inJustDecodeBounds = true;
	    
	    InputStream stream = fetchStream(url);
	    BitmapFactory.decodeStream(stream, null, options);
	    stream.close();

	    // Calculate inSampleSize
	    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
	    // Decode bitmap with inSampleSize set
	    options.inJustDecodeBounds = false;
	    
	    stream = fetchStream(url);
	    Bitmap bitmap = BitmapFactory.decodeStream(stream, null, options);
	    stream.close();
	    
	    return bitmap;
	}
	
	private static InputStream fetchStream(String urlString) throws IllegalStateException, IOException {
		
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpGet request = new HttpGet(urlString);
		HttpResponse response = httpClient.execute(request);
		return response.getEntity().getContent();
	}
	
	private static int calculateInSampleSize(Options options, int reqWidth, int reqHeight) {
		// Raw height and width of image
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {

			// Calculate ratios of height and width to requested height and width
			final int heightRatio = Math.round((float) height / (float) reqHeight);
			final int widthRatio = Math.round((float) width / (float) reqWidth);

			// Choose the smallest ratio as inSampleSize value, this will guarantee
			// a final image with both dimensions larger than or equal to the
			// requested height and width.
			inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
		}

		return inSampleSize;
	}

註意:通過Bitmap.createBitmap生成的Bitmap對象是可變對象,可以向Bitmap上繪制內容,而通過BitmapFactory生成的Bitmap對象必須指定BitmapFactory.Options.inMutable = true,否則就是不可變對象,不能向上面繪制內容。

感謝大傢的支持,如有錯誤請指正,如需轉載請標明原文出處!

到此這篇關於Android Canvas和Bitmap結合繪圖詳解流程的文章就介紹到這瞭,更多相關Android 繪圖內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: