android 设置壁纸变黑,【android】把view保存为图片的方法以及解决保存后图片背景变黑色的问题...

博客给出Android代码示例,展示将ImageView内容保存为图片的过程。强调调用getDrawingCache()前需测量,否则bitmap为null。还指出使用JPEG格式保存图片时背景会变黑,将压缩格式改为PNG即可解决该问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上代码:

public class MainActivity extends Activity {

ImageView imgView;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

imgView = (ImageView) findViewById(R.id.imageView);

imgView.setDrawingCacheEnabled(true);

// this is the important code :)

// Without it the view will have a dimension of 0,0 and the bitmap will be null

imgView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),

MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));

imgView.layout(0, 0, imgView.getMeasuredWidth(), imgView.getMeasuredHeight());

Bitmap bitmap = Bitmap.createBitmap(imgView.getDrawingCache());

imgView.setDrawingCacheEnabled(false);

String strPath ="/testSaveView/"+UUID.randomUUID().toString()+".png";

if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))

{

File sdCardDir=Environment.getExternalStorageDirectory();

FileOutputStream fos = null;

try{

File file = new File(sdCardDir,strPath);

if (!file.getParentFile().exists()) {

file.getParentFile().mkdirs();

}

fos = new FileOutputStream(file);

//当指定压缩格式为PNG时保存下来的图片显示正常

bitmap.compress(CompressFormat.JPEG, 100, fos);

//当指定压缩格式为JPEG时保存下来的图片背景为黑色

// bitmap.compress(CompressFormat.JPEG, 100, fos);

fos.flush();

}catch(Exception e){

e.printStackTrace();

}finally{

try {

fos.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

}

activity_main.xml:

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical">

android:id="@+id/imageView"

android:layout_width="100dp"

android:layout_height="100dp"

android:scaleType="centerInside"

android:src="@drawable/ic_launcher"/>

需要注意两个问题:

一、调用getDrawingCache()前先要测量,否则的话得到的bitmap为null,这个我在OnCreate()、OnStart()、OnResume()方法里都试验过。

二、当调用bitmap.compress(CompressFormat.JPEG, 100, fos);保存为图片时发现图片背景为黑色,如下图:

429cdfc62b2963eb508070cb546321f8.png

这时只需要改成用png保存就可以了,bitmap.compress(CompressFormat.PNG, 100, fos);,如下图:

38be0cafc96445177fe197bb2f3ae37e.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值