package com.example.bitmapcreate; import java.io.ByteArrayOutputStream; import android.util.Log; import android.os.Bundle; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.view.Menu; import android.view.View; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(new SampleView(this)); } private class SampleView extends View{ private Bitmap[] mBitmaps; private int[] mColors; private Paint mPaint; private static final int WIDTH=200; private static final int HEIGHT=150; private static final int STRIDE=WIDTH+50;//must be >=WIDTH public SampleView(Context context) { super(context); setFocusable(true); mColors = initColorss(); mBitmaps=new Bitmap[2]; mPaint=new Paint(); mPaint.setDither(true); mBitmaps[0]=Bitmap.createBitmap(mColors, 0, STRIDE, WIDTH, HEIGHT, Config.ARGB_8888); mBitmaps[1]=Bitmap.createBitmap(mColors, 250, STRIDE, WIDTH, HEIGHT, Config.ARGB_8888); } @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub super.onDraw(canvas); canvas.drawColor(Color.WHITE); for (int i = 0; i < mBitmaps.length; i++) { canvas.drawBitmap(mBitmaps[i], 0, 0, null); canvas.translate(0, mBitmaps[i].getHeight()); } } private int[] initColorss() { int[] colors = new int[(STRIDE+50)*HEIGHT]; for(int i=0;i<HEIGHT;i++) { for(int j=0;j<WIDTH;j++) { int r = 2*j%255; int g = r; int b = r; int a = 100; colors[i*STRIDE+j]=(a<<24)|(r<<16)|(g<<8)|(b); for (int k=WIDTH;k<STRIDE+50;k++) { colors[i*STRIDE+k] = -2578654; } } } return colors; } } }
现在来探讨offset跟stride作用以及相互关系。
在上面的程序中,我们设置位图大小为200*150,设置stride = 200 + 50;设置colors数组大小为(stride+50)*150 = 300*150
这种情况下我们是 colors宽度 > stride宽度 > bitmap宽度
(1) 设置offset = 25,50,100,200,250,300,350,450,500
offset =25 offset = 50 offset = 100
offset =200 offset = 250 offset = 300
offset =350 offset = 450 offset = 500
(2)当colors宽度 = Stride宽度时候
此时就比较蹊跷了,max(offset)= stride – width,
当超过这个max值时候,程序就不能正常启动了。
(3)当colors宽度 < stride 宽度时候
程序一样的不能运行。
综上所示,可得:
1:colors 宽度 >= stride >= bitmap 宽度
2:当colors宽度 = stride时,offset最大值 = stride – 位图width
3:当colors宽度 > stride时,offset可以为任意值,此时位图的实际偏移量=
Offset%stride,此时的位图就是从offset%stride开始,
将offset%stride之前的位图区域挪到stride边界的后面。