Android 不可见View生成Bitmap转图片显示

1.异步加载布局上的图片显示

使用加载方式Glide

    implementation('com.github.bumptech.glide:glide:4.7.1') {
        exclude group: "com.android.support"
    }
    annotationProcessor 'com.github.bumptech.glide:compiler:4.7.1'

2.测试布局activity_second.xml




    

3.传异步加载图片

3.1计算view的大小
    public void measureSize(Activity activity, String url) {
        //将布局转化成view对象
        View viewBitmap = LayoutInflater.from(activity).inflate(R.layout.activity_second, null);
        View viewById = viewBitmap.findViewById(R.id.rl);
        WindowManager manager = activity.getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        int width = outMetrics.widthPixels;
        int height = outMetrics.heightPixels;

        //然后View和其内部的子View都具有了实际大小,也就是完成了布局,相当与添加到了界面上。接着就可以创建位图并在上面绘制了:
        layoutView(viewById, width, height, url, activity);
    }
3.2填充布局内容
    public void layoutView(final View viewBitmap, int width, int height, String url, Activity activity) {
        // 整个View的大小 参数是左上角 和右下角的坐标
        viewBitmap.layout(0, 0, width, height);
        int measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
        int measuredHeight = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.AT_MOST);

    viewBitmap.measure(measuredWidth, measuredHeight);
    viewBitmap.layout(0, 0, viewBitmap.getMeasuredWidth(), viewBitmap.getMeasuredHeight());

    final ImageView imageView = viewBitmap.findViewById(R.id.iv_show);

    //注意加载网络图片时一定要用SimpleTarget回调
    Glide.with(activity).asBitmap().load(url).into(new SimpleTarget() {
        @Override
        public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition transition) {
            imageView.setImageBitmap(resource);
            Bitmap bitmap = viewSaveToImage(viewBitmap);
            ivShow2.setImageBitmap(bitmap);

            llBottom.setBackgroundColor(Color.parseColor("#dddddd"));
        }
    });
}
3.3把view转成图片
private Bitmap viewSaveToImage(View view) {
    view.setDrawingCacheEnabled(true);
    view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
    view.setDrawingCacheBackgroundColor(Color.WHITE);

    // 把一个View转换成图片
    Bitmap cachebmp = viewConversionBitmap(view);

//        if (mBitmapDoneListener != null){
//            mBitmapDoneListener.bitmapDone(cachebmp);
//        }

    view.destroyDrawingCache();

    return cachebmp;
}
3.4view转bitmap
 public Bitmap viewConversionBitmap(View v) {
        int w = v.getWidth();
        int h = v.getHeight();

        if (w <=0 || h<=0) {
            Toast.makeText(this, "view's width or height are <= 0", Toast.LENGTH_SHORT).show();
            return null;
        }


        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);

        c.drawColor(Color.WHITE);
        /** 如果不设置canvas画布为白色,则生成透明 */

        v.layout(0, 0, w, h);
        v.draw(c);

        return bmp;
    }
3.5 把上面获得的bitmap传进来就可以得到圆角的bitmap了
public void bitmapInBitmap(Bitmap bitmap, ImageView imageView) {
    Bitmap tempBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
    Canvas canvas = new Canvas(tempBitmap);

    //图像上画矩形
    Paint paint = new Paint();
    paint.setColor(Color.TRANSPARENT);
    paint.setStyle(Paint.Style.STROKE);//不填充
    paint.setStrokeWidth(10);  //线的宽度
    canvas.drawRect(10, 20, 100, 100, paint);
    imageView.setImageBitmap(tempBitmap);

    //画中画
    Paint photoPaint = new Paint(); // 建立画笔
    photoPaint.setDither(true); // 获取跟清晰的图像采样
    photoPaint.setFilterBitmap(true);// 过滤一些

    Rect src = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());// 创建一个指定的新矩形的坐标
    Rect dst = new Rect(0, 0, 300, 350);// 创建一个指定的新矩形的坐标
    canvas.drawBitmap(tempBitmap, src, dst, photoPaint);// 将photo 缩放或则扩大到
    imageView.setImageBitmap(getRoundedCornerBitmap(tempBitmap));
}
3.6 生成圆角图片
public Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
    try {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(),
                bitmap.getHeight());
        final RectF rectF = new RectF(new Rect(0, 0, bitmap.getWidth(),
                bitmap.getHeight()));
        //设置圆角大小
        final float roundPx = 30;
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.BLACK);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        final Rect src = new Rect(0, 0, bitmap.getWidth(),
                bitmap.getHeight());
        canvas.drawBitmap(bitmap, src, rect, paint);
        return output;
    } catch (Exception e) {
        return bitmap;
    }
}

4.总结页面显示SecondActivity

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by GetOn on 2019/3/11.
 */

public class SecondActivity extends AppCompatActivity {


    @BindView(R.id.btn)
    Button btn;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R.id.ll_top)
    LinearLayout llTop;
    @BindView(R.id.iv_show)
    ImageView ivShow;
    @BindView(R.id.iv_show2)
    ImageView ivShow2;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_second);
        ButterKnife.bind(this);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                measureSize(SecondActivity.this, "http://www.pptbz.com/pptpic/UploadFiles_6909/201203/2012031220134655.jpg");

            }
        });


    }


    /**
     * 计算view的大小
     */
    public void measureSize(Activity activity, String url) {
        //将布局转化成view对象
        View viewBitmap = LayoutInflater.from(activity).inflate(R.layout.activity_second, null);
        View viewById = viewBitmap.findViewById(R.id.rl);
        WindowManager manager = activity.getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        int width = outMetrics.widthPixels;
        int height = outMetrics.heightPixels;

        //然后View和其内部的子View都具有了实际大小,也就是完成了布局,相当与添加到了界面上。接着就可以创建位图并在上面绘制了:
        layoutView(viewById, width, height, url, activity);
    }

    /**
     * 填充布局内容
     */
    public void layoutView(final View viewBitmap, int width, int height, String url, Activity activity) {
        // 整个View的大小 参数是左上角 和右下角的坐标
        viewBitmap.layout(0, 0, width, height);
        int measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
        int measuredHeight = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.AT_MOST);

        viewBitmap.measure(measuredWidth, measuredHeight);
        viewBitmap.layout(0, 0, viewBitmap.getMeasuredWidth(), viewBitmap.getMeasuredHeight());

        final ImageView imageView = viewBitmap.findViewById(R.id.iv_show);

        //注意加载网络图片时一定要用SimpleTarget回调
        Glide.with(activity).asBitmap().load(url).into(new SimpleTarget() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition transition) {
                imageView.setImageBitmap(resource);
                Bitmap bitmap = viewSaveToImage(viewBitmap);
                ivShow2.setImageBitmap(bitmap);

                llBottom.setBackgroundColor(Color.parseColor("#dddddd"));
            }
        });
    }


    /**
     * 把view转成图片
     *
     * @param view
     */
    private Bitmap viewSaveToImage(View view) {
        view.setDrawingCacheEnabled(true);
        view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
        view.setDrawingCacheBackgroundColor(Color.WHITE);

        // 把一个View转换成图片
        Bitmap cachebmp = viewConversionBitmap(view);

//        if (mBitmapDoneListener != null){
//            mBitmapDoneListener.bitmapDone(cachebmp);
//        }

        view.destroyDrawingCache();

        return cachebmp;
    }


    /**
     * view转bitmap
     */
    public Bitmap viewConversionBitmap(View v) {
        int w = v.getWidth();
        int h = v.getHeight();

        if (w <=0 || h<=0) {
            Toast.makeText(this, "view's width or height are <= 0", Toast.LENGTH_SHORT).show();
            return null;
        }


        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);

        c.drawColor(Color.WHITE);
        /** 如果不设置canvas画布为白色,则生成透明 */

        v.layout(0, 0, w, h);
        v.draw(c);

        return bmp;
    }

    /**
     * 把上面获得的bitmap传进来就可以得到圆角的bitmap了
     */
    public void bitmapInBitmap(Bitmap bitmap, ImageView imageView) {
        Bitmap tempBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
        Canvas canvas = new Canvas(tempBitmap);

        //图像上画矩形
        Paint paint = new Paint();
        paint.setColor(Color.TRANSPARENT);
        paint.setStyle(Paint.Style.STROKE);//不填充
        paint.setStrokeWidth(10);  //线的宽度
        canvas.drawRect(10, 20, 100, 100, paint);
        imageView.setImageBitmap(tempBitmap);

        //画中画
        Paint photoPaint = new Paint(); // 建立画笔
        photoPaint.setDither(true); // 获取跟清晰的图像采样
        photoPaint.setFilterBitmap(true);// 过滤一些

        Rect src = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());// 创建一个指定的新矩形的坐标
        Rect dst = new Rect(0, 0, 300, 350);// 创建一个指定的新矩形的坐标
        canvas.drawBitmap(tempBitmap, src, dst, photoPaint);// 将photo 缩放或则扩大到
        imageView.setImageBitmap(getRoundedCornerBitmap(tempBitmap));
    }

    /**
     * 生成圆角图片
     */
    public Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
        try {
            Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                    bitmap.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(output);
            final Paint paint = new Paint();
            final Rect rect = new Rect(0, 0, bitmap.getWidth(),
                    bitmap.getHeight());
            final RectF rectF = new RectF(new Rect(0, 0, bitmap.getWidth(),
                    bitmap.getHeight()));
            //设置圆角大小
            final float roundPx = 30;
            paint.setAntiAlias(true);
            canvas.drawARGB(0, 0, 0, 0);
            paint.setColor(Color.BLACK);
            canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
            final Rect src = new Rect(0, 0, bitmap.getWidth(),
                    bitmap.getHeight());
            canvas.drawBitmap(bitmap, src, rect, paint);
            return output;
        } catch (Exception e) {
            return bitmap;
        }
    }
}

//备份使用

你可能感兴趣的:(Android常用)