mus*_*usa 2 performance android galleryview
我正在使用带有~40张图像的GalleryView,因为没有回收......所以很慢...
谁能告诉我一个基本的循环利用GalleryView上的getView方法.
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;
private Integer[] mImageIds = {
R.drawable.sample_1,
R.drawable.sample_2,
R.drawable.sample_3,
R.drawable.sample_4,
R.drawable.sample_5,
R.drawable.sample_6,
R.drawable.sample_7
};
public ImageAdapter(Context c) {
mContext = c;
TypedArray a = c.obtainStyledAttributes(R.styleable.HelloGallery);
mGalleryItemBackground = a.getResourceId(
R.styleable.HelloGallery_android_galleryItemBackground, 0);
a.recycle();
}
public int getCount() {
return mImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageResource(mImageIds[position]);
i.setLayoutParams(new Gallery.LayoutParams(150, 100));
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setBackgroundResource(mGalleryItemBackground);
return i;
}
}
Run Code Online (Sandbox Code Playgroud)
而不是创建一个新ImageView的getView,你应该转换convertView到你想要的视图.以下是一种方法示例:
public View getView(int position, View cv, ViewGroup parent) {
if (! convertView istanceof ImageView)
{
ImageView cv = new ImageView(mContext);
cv.setLayoutParams(new Gallery.LayoutParams(150, 100));
cv.setScaleType(ImageView.ScaleType.FIT_XY);
cv.setBackgroundResource(mGalleryItemBackground);
}
cv.setImageResource(mImageIds[position]);
return cv;
}
Run Code Online (Sandbox Code Playgroud)
只需转换convertView以匹配您想要的,但首先要确保其正确的视图类型.
更新:您还应该在显示图像之前对图像进行下采样.让我们假设您保存了500x500像素的图像,res/drawable但图像只占用屏幕上的125x125像素.在显示图像之前,您需要对图像进行下采样.要知道您需要对位图进行下采样,您必须首先获得其大小
int maxSize = 125; // make 125 the upper limit on the bitmap size
int resId; // points to bitmap in res/drawable
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true; // Only get the bitmap size, not the bitmap itself
BitmapFactory.decodeResource(c.getResources(), resId, opts);
int w = opts.outHeight, h = opts.outHeight;
int maxDim = (w>h)?w:h; // Get the bigger dimension
Run Code Online (Sandbox Code Playgroud)
现在我们有了大小来计算对图像进行下采样的程度.如果我们有一个500x500的位图,并且我们想要一个125x125的位图,那么我们保留每4个像素中的1个int inSample = 500/125;
int inSample = maxDim/maxSize;
opts = new BitmapFactory.Options();
opts.inSampleSize = inSample;
Run Code Online (Sandbox Code Playgroud)
现在简单地解码资源,我们有下采样的位图.
Bitmap b = BitmapFactory.decodeResource(c.getResources(), resId, opts);
Run Code Online (Sandbox Code Playgroud)
请记住,原始位图不受影响.您可以再次解码图像并设置opts.inSampleSize为1,您将获得整个500x500位图图像.
| 归档时间: |
|
| 查看次数: |
3968 次 |
| 最近记录: |