一:使用HttpURLConnection,Bitmap,Canvas,测试withcontent线程以及回调
1. 效果图
- 设置一张默认图片
- 图片加载后
2. 实现代码一,参考出处:参考了微信:小楠总
1. 协程导包
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.1"implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.1"
- ViewBinding导包(gradle->android)
buildFeatures {
viewBinding true}
- 网络权限导包
<uses-permission android:name="android.permission.INTERNET"/>
2. Main代码
- 开启了一个主协程,内部切了两个IO协程的方法
- 运用了Canvas和Paint,这边如果不想加水印字体的话不用调用第二个方法,直接设置就行
class MainActivity : AppCompatActivity() {
val TAG="MainAC"override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)var binding= ActivityMainBinding.inflate(layoutInflater)setContentView(binding.root)CoroutineScope(Dispatchers.Main).launch {
Log.d(TAG, "onCreate: 当前线程为${
Thread.currentThread().name}")val bitmap=getImageFromNet()Log.d(TAG, "onCreate 返回的bitmap: $bitmap")val bitmapcreate=createBT(bitmap,"夏鱼")Log.d(TAG, "onCreate 返回的bitmapcreate: $bitmapcreate")binding.imageView.setImageBitmap(bitmapcreate)}}private suspend fun getImageFromNet()=withContext(Dispatchers.IO){
Log.d(TAG, "getImageFromNet: 当前线程为${
Thread.currentThread().name}")val url = URL("https://picjumbo.com/wp-content/uploads/white-swans-near-charles-bridge-in-prague-2210x1473.jpg")val connection=url.openConnection() as HttpURLConnectionval inputStream=connection.inputStreamBitmapFactory.decodeStream(inputStream)}private suspend fun createBT(bitmap: Bitmap, mark:String)=withContext(Dispatchers.IO){
Log.d(TAG, "createBT: 当前线程为${
Thread.currentThread().name}")val w=bitmap.widthval h=bitmap.heightval bmp=Bitmap.createBitmap(w,h,Bitmap.Config.ARGB_8888)val canvas=Canvas(bmp)val paint=Paint()paint. color= Color.parseColor( "#ffffff")paint.textSize=150Fpaint.isAntiAlias=truecanvas.drawBitmap(bitmap,0f, 0f, paint)canvas.drawText(mark,0f,(h/2).toFloat(),paint)canvas.save()canvas.restore()return@withContext bmp}}
- 从这里我们得知主协程命令,在切换IO协程结束后会切回主协程,之后开启的协程将和之前的一样(阻塞机制和协程结束机制)
- 观察发现 第一个函数没有返回值,第二个函数有返回值。但打印都没问题,原因是赋值机制。
2. 改为Retrofit
1. 定义AppService接口接口