1public class MainActivity extends AppCompatActivity {
2
3 private ImageView mImageView;
4 @Override
5 protected void onCreate(Bundle savedInstanceState) {
6 super.onCreate(savedInstanceState);
7 setContentView(R.layout.activity_main);
8 mImageView = (ImageView) findViewById(R.id.image);
9 }
10
11 // 给图片加水印的方法
12 private Bitmap createWatermark(Bitmap bitmap, String mark) {
13 int w = bitmap.getWidth();
14 int h = bitmap.getHeight();
15 Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
16 Canvas canvas = new Canvas(bmp);
17 Paint p = new Paint();
18 // 水印颜色
19 p.setColor(Color.parseColor("#C5FF0000"));
20 // 水印字体大小
21 p.setTextSize(150);
22 //抗锯齿
23 p.setAntiAlias(true);
24 //绘制图像
25 canvas.drawBitmap(bitmap, 0, 0, p);
26 //绘制文字
27 canvas.drawText(mark, 0, h / 2, p);
28 canvas.save(Canvas.ALL_SAVE_FLAG);
29 canvas.restore();
30 return bmp;
31 }
32}
1new Thread(new Runnable() {
2 @Override
3 public void run() {
4 try {
5 URL url = new URL("https://www.baidu.com/img/bd_logo1.png?where=super");
6 HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
7 InputStream inputStream = urlConnection.getInputStream();
8 Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
9 // 加一个水印
10 bitmap = createWatermark(bitmap,"RxJava2.0");
11 // 显示到图片
12 Message message = Message.obtain();
13 message.obj = bitmap;
14 mHandler.sendMessage(message);
15 } catch (IOException e) {
16 e.printStackTrace();
17 }
18 }
19}).start();
20
21private Handler mHandler = new Handler(){
22 @Override
23 public void handleMessage(Message msg) {
24 Bitmap bitmap = (Bitmap) msg.obj;
25 mImageView.setImageBitmap(bitmap);
26 }
27}
1Observable.just("https://www.baidu.com/img/bd_logo1.png?where=super")
2 .map(new Function<String, Bitmap>() { // 事件变换
3
4 @Override
5 public Bitmap apply(@NonNull String urlPath) throws Exception {
6 URL url = new URL(urlPath);
7 HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
8 InputStream inputStream = urlConnection.getInputStream();
9 Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
10 return bitmap;
11 }
12 })
13 .map(new Function<Bitmap, Bitmap>() {
14
15 @Override
16 public Bitmap apply(@NonNull Bitmap bitmap) throws Exception {
17 bitmap = createWatermark(bitmap, "RxJava2.0");
18 return bitmap;
19 }
20 })
21 .subscribeOn(Schedulers.io())
22 .observeOn(AndroidSchedulers.mainThread())
23 .subscribe(new Consumer<Bitmap>() {
24
25 @Override
26 public void accept(Bitmap bitmap) throws Exception {
27 mImageView.setImageBitmap(bitmap);
28 }
29 });
实现优雅:链式调用,一点到底
逻辑简洁:代码可读性高,解耦
使用简单:支持线程调度和各种操作符
扩展维护:随着程序逻辑的复杂性提高,它依然能够保持简洁和优雅
扩展维护:随着程序逻辑的复杂性提高,它依然能够保持简洁和优雅