参数的含义:
Bitmap bitmap:需要处理的图片
Rect src:图片的坐标
RectF dst:需要绘制的图片所在位置的坐标
Paint paint:画笔类(处理图片时一般为null)
下面来介绍下Rect和RectF
android.graphics.RectF
android.graphics.Rect
From interface android.os.Parcelable
android.graphics.RectF
android.graphics.Rect
From interface android.os.Parcelable
两个类都有四个public属性,分别为bottom,left,top,right,使用它们Java代码如下:
Rect dst = new Rect(); // 图片坐标
dst. left = A;
dst. top = B;
dst. right = C;
dst. bottom = D;
RectF dst = new RectF(); // 屏幕坐标
dst. left = E;
dst. top = F;
dst. right = G;
dst. bottom = H;
你可能会疑惑这些坐标都代表了什么意思。首先,一张图片肯定是以一个矩形的方式放在屏幕上的,那么如何定位这个矩形呢
,我们需要以下几个坐标:
矩形左端边线的X轴坐标值 | Rect.left, RectF.left |
矩形右端边线的X轴坐标值 | Rect.right, RectF.right |
矩形上端的Y轴坐标值 | Rect.top, RectF.top |
矩形下端的Y轴坐标值 | Rect.bottom, RectF.bottom |
了解了这些坐标的含义之后,我们再来看看drawBitmap中是如何使用这些坐标的。
src参数:图片所在矩形的坐标。
例如,我有一张长120像素,宽80像素的图片,那么久可以新建这个坐标为:
Rect src = new Rect(); // 图像内的坐标
src. left = 0;
src. top = 0;
src. right = 120;
src. bottom = 80;
dst参数:图片需要摆放的坐标
例如,我需要把src图片摆放到屏幕左浮动20像素,向下浮动40像素的位置上
RectF dst = new Rect(); // 图像内的坐标
dst. left = 20;
dst. top = 40;
dst. right = 120+20;
dst. bottom = 80+40;
就是说把图片的left坐标放在屏幕的left坐标上,其他点的坐标也一样。
如果你需要对图片变形或者拉伸,就可以控制dst的坐标。
以下是所用到的类,用于一个书架排版的页面适应更宽的屏幕(使背景图片拉伸)
package com . vision . agriculture . classes . repository ;
import android . content . Context ;
import android . graphics . Bitmap ;
import android . graphics . BitmapFactory ;
import android . graphics . Canvas ;
import android . graphics . Rect ;
import android . graphics . RectF ;
import android . util . AttributeSet ;
import android . widget . GridView ;
import com . vision . agriculture . R ;
public class MyGridView extends GridView {
private Bitmap background ;
public MyGridView ( Context context , AttributeSet attrs ) {
super ( context , attrs );
background = BitmapFactory . decodeResource ( getResources (),
R . drawable . repo_gridview_layer_bg );
}
@Override
protected void layoutChildren () {
super . layoutChildren ();
}
@Override
protected void onMeasure ( int widthMeasureSpec , int heightMeasureSpec ) {
super . onMeasure ( widthMeasureSpec , heightMeasureSpec );
}
@Override
protected void dispatchDraw ( Canvas canvas ) {
int count = getChildCount ();
int top = count > 0 ? getChildAt ( 0 ). getTop () : 0 ;
int backgroundWidth = background . getWidth ();
int backgroundHeight = background . getHeight ();
int width = getWidth ();
int height = getHeight ();
final Rect src = new Rect (); // 图像内的坐标
src . left = 0 ;
src . top = 0 ;
src . right = backgroundWidth ;
src . bottom = backgroundHeight ;
for ( int y = top ; y < height ; y += backgroundHeight ) {
RectF dst = new RectF (); //屏幕
dst . left = 0 ;
dst . top = y ;
dst . right = width ;
dst . bottom = y + backgroundHeight ;
canvas . drawBitmap ( background , src , dst , null );
}
super . dispatchDraw ( canvas );
}
}