Android java设置图片颜色
时间: 2023-10-02 12:03:24 浏览: 46
可以使用ColorFilter来改变图片的颜色。以下是一个示例代码:
```
ImageView imageView = findViewById(R.id.image_view);
Drawable drawable = imageView.getDrawable();
drawable.setColorFilter(new PorterDuffColorFilter(ContextCompat.getColor(this, R.color.colorPrimary), PorterDuff.Mode.SRC_ATOP));
```
在上面的代码中,首先获取ImageView中的Drawable,然后使用PorterDuffColorFilter将颜色应用到Drawable上。PorterDuff.Mode.SRC_ATOP表示将颜色应用于Drawable上方的像素。在这个例子中,颜色定义在colors.xml文件中的colorPrimary。
相关问题
android bitmapdrawable 设置颜色
可以使用 `setColor()` 方法来设置 `BitmapDrawable` 的颜色。下面是一个示例代码:
```java
BitmapDrawable drawable = (BitmapDrawable) getResources().getDrawable(R.drawable.image);
drawable.setColorFilter(Color.RED, PorterDuff.Mode.SRC_IN);
```
上面的代码会将 `R.drawable.image` 图片的颜色设置为红色。其中,`setColorFilter()` 方法接受两个参数:第一个参数是颜色,第二个参数是 `PorterDuff.Mode`,它定义了颜色过滤器的模式。在这个示例中,我们使用的是 `PorterDuff.Mode.SRC_IN`,它表示只显示源图像和目标图像重叠的部分,并将其它区域设置为透明。这样就可以将颜色应用到图片中了。
Android设置图片为圆形
在 Android 中,可以通过以下步骤将图片设置为圆形:
1. 首先,将图片加载到一个 Bitmap 对象中。
2. 创建一个新的 Bitmap 对象,它的宽度和高度与原始图片相同。
3. 创建一个 Canvas 对象,将新的 Bitmap 对象传递给它。
4. 创建一个 Paint 对象,设置颜色和样式。
5. 使用 Canvas 对象和 Paint 对象将原始图片绘制到新的 Bitmap 对象上。
6. 将新的 Bitmap 对象设置为 ImageView 的源。
下面是一个示例代码:
```java
public static Bitmap getCircleBitmap(Bitmap bitmap) {
final Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(output);
final int color = Color.RED;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawOval(rectF, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
bitmap.recycle();
return output;
}
```
这个方法接收一个 Bitmap 对象作为参数,然后返回一个圆形的 Bitmap 对象。你可以将返回的 Bitmap 对象设置为 ImageView 的源来显示圆形图片。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)