一:使用HttpURLConnection,Bitmap,Canvas,测试withcontent线程以及回调
1. 效果图
- 设置一张默认图片
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/106d5c80e6bcfd4bcd9161a89f800cf3.png)
- 图片加载后
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/54b16f5c8ebddf203d8704cb1910d94d.png)
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 HttpURLConnection
val inputStream=connection.inputStream
BitmapFactory.decodeStream(inputStream)
}
private suspend fun createBT(bitmap: Bitmap, mark:String)=
withContext(Dispatchers.IO){
Log.d(TAG, "createBT: 当前线程为${Thread.currentThread().name}")
val w=bitmap.width
val h=bitmap.height
val bmp=Bitmap.createBitmap(w,h,Bitmap.Config.ARGB_8888)
val canvas=Canvas(bmp)
val paint=Paint()
paint. color= Color.parseColor( "#ffffff")
paint.textSize=150F
paint.isAntiAlias=true
canvas.drawBitmap(bitmap,0f, 0f, paint)
canvas.drawText(mark,0f,(h/2).toFloat(),paint)
canvas.save()
canvas.restore()
return@withContext bmp
}
}
- 从这里我们得知主协程命令,在切换IO协程结束后会切回主协程,之后开启的协程将和之前的一样(阻塞机制和协程结束机制)
- 观察发现 第一个函数没有返回值,第二个函数有返回值。但打印都没问题,原因是赋值机制。
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/1834bf98f0001055d27950e944dccc4a.png)
2. 改为Retrofit
1. 定义AppService接口接口