我正在绘制一些位图到ImageView的画布上。资源位图是彩色的。结果,我想看到的是一个灰度比例尺的位图,是倒置的。
这是我在三星Galaxy (4.1.2版)上完美地工作的方法,但它不能在我的S3 Mini上工作。
在覆盖的OnDraw(画布画布)方法中:
// Night mode color:
Paint colorBMPPaint = new Paint();
if (((EzPdfActivityPageView) mContext).bIsNightMode) {
float invertMX[] = {
0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f, 0.0f
};
ColorMatrix invertCM = new ColorMatrix(invertMX);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(invertCM);
colorBMPPaint.setColorFilter(filter);
}
canvas.drawBitmap(bitmap,
new Rect(0, 0, (int)((bbox.right - bbox.left) * zoom), (int)((bbox.top - bbox.bottom) * zoom)),
pageDrawRect,
colorBMPPaint);在S3 Mini上,我只得到黑色位图,为什么?
发布于 2016-10-26 19:59:23
你确定你的矩阵设置正确了吗?
根据ColorMatrix文档,您的输入矩阵定义如下:
4x5矩阵,用于转换位图的颜色和α分量。矩阵可以作为单个数组传递,并按以下方式处理: a,b,c,d,e, f,g,h,i,j, k,l,m,n,o, p,q,r,s,t 当将其应用于颜色R、G、B、A时,生成的颜色计算为: R‘= a_R + b_G + c_B + d_A + e; G‘= f_R + g_G + h_B + i_A + j; B‘= k_R + l_G + m_B + n_A + o; A‘= p_R + q_G + r_B + s_A + t;
在你的矩阵中,r等于1.0f,其余的是0f。根据这一点,只有alpha通道将是非零,因此黑色似乎是预期的输出。
相反,您可以执行以下操作:
ColorMatrix matrix = new ColorMatrix(); matrix.setSaturation(0);
顺便说一句,在执行onDraw()时分配对象(如矩阵)不利于性能。如果可以,可以将分配移动到构造函数或其他地方。
更新:对于倒置部分,您可以应用一个额外的矩阵(或者按这里中描述的矩阵相乘,或者只绘制两次位图(效率较低)。逆矩阵应该是-
ColorMatrix colorMatrix_Inverted = new ColorMatrix(new float[] { -1, 0, 0, 0, 255, 0, -1, 0, 0, 255, 0, 0, -1, 0, 255, 0, 0, 0, 1, 0});
发布于 2016-10-26 20:24:28
根据@Doron Yakovlev-Golani的建议,我已经编辑了我的代码,这一个现在正在两种设备上工作:
float invertMX[] = {
-1.0f, 0.0f, 0.0f, 0.0f, 255f,
0.0f, -1.0f, 0.0f, 0.0f, 255f,
0.0f, 0.0f, -1.0f, 0.0f, 255f,
0.0f, 0.0f, 0.0f, 1.0f, 0.0f
};
ColorMatrix saturationZero = new ColorMatrix();
saturationZero.setSaturation(0);
ColorMatrix finalCM = new ColorMatrix(saturationZero);
ColorMatrix invertCM = new ColorMatrix(invertMX);
finalCM.postConcat(invertCM);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(finalCM);
colorBMPPaint.setColorFilter(filter);发布于 2016-10-26 20:27:57
这对我来说很管用:
for (int x = 0; x < bm.getWidth(); ++x) {
for (int y = 0; y < bm.getHeight(); ++y) {
int color = bm.getPixel(x, y);
int r = Color.red(color);
int g = Color.green(color);
int b = Color.blue(color);
int avg = (r + g + b) / 3;
int newColor = Color.argb(255, 255 - avg, 255 - avg, 255 - avg);
bm.setPixel(x, y, newColor);
}
}请注意,您的位图必须是可变的,才能对其进行操作,这可能是有用的。如果不是,您可以这样做来创建一个可变副本:
bm = bm.copy(bm.getConfig(), true);https://stackoverflow.com/questions/40270908
复制相似问题