3月 21, 2020 Android
### Picasso

Picasso 是一個用來載入圖片的程式庫,可以用來處理從 HTTP 的檔案,能夠輕鬆處理 RecyclerView 的 Async 圖片載入行為。

> Picasso 網址 : https://square.github.io/picasso

### 問題

在使用 Picasso 載入圖片時,可能會遇到以下這個問題 :

```java
Picasso.get()
	.load("https://example.com/image.jpg")
	.centerCrop()
	.into(mImageView);
```

在 Runtime 時會出以下的 Exception :

```text
Center inside requires calling resize with positive width and height
```

原因是因為 Picasso 要把圖片載入到 Image View 時,要先把 Bitmap resize 為一個正數的數值,才能夠使用 `center inside` 或 `center crop`。但是我們應該要 resize 做什麼數值才好呢?

### 解決方法

通過使用 `.resize()` 方法,可以把 Bitmap resize 為一個正數值的大小。

```java
Picasso.get()
	.load("https://example.com/image.jpg")
	.resize(800, 800)
	.centerCrop()
	.into(mImageView);
```

以上的代碼是能夠運行,但是好像欠缺彈性。我們可以使用 `.fit()` 方法來讓 Picasso 幫我們自動 resize 為 Image View 的大小,這讓我們就不用 hard code 數值到 `.resize()` 了。

```java
Picasso.get()
	.load("https://example.com/image.jpg")
	.fit()
	.centerCrop()
	.into(mImageView);
```
過去文章
2025 (9)
4 (5)
3 (1)
2 (3)
2024 (25)
11 (3)
10 (3)
9 (1)
3 (18)
2022 (6)
10 (1)
6 (2)
5 (1)
3 (1)
1 (1)
2021 (21)
11 (7)
7 (1)
6 (2)
5 (2)
4 (6)
3 (2)
2 (1)
2020 (92)
12 (1)
11 (2)
10 (4)
9 (10)
8 (5)
7 (1)
6 (3)
5 (1)
4 (4)
3 (25)
2 (7)
1 (29)
2019 (57)
12 (25)
11 (7)
9 (25)