问题
I'm creating a custom view on Android, but the rendered colour is always grey no matter how I try to change it.
private void init() {
Resources res = mContext.getResources();
float density = res.getDisplayMetrics().density;
mBackgroundWidth = (int)(DEFAULT_WIDTH * density); // default to 20dp
mPrimaryColor = gaugeColour;
mPrimaryWidth = (int)(DEFAULT_WIDTH * density); // default to 20dp
x_Corner=30*density;
y_Corner=30*density;
mRegularTextSize = (int)(mBackgroundWidth * 0.75); //Double the size of the width;
mRectPaintPrimary = new Paint() {
{
setDither(true);
setStyle(Style.FILL);
setStrokeCap(Cap.ROUND);
setAntiAlias(true);
}
};
mRectPaintPrimary.setColor(mPrimaryColor);
//code for text formatting followed
}
And this is the onDraw function
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);// bound our drawable Rect to stay fully within our canvas
float left=0,top=0,right=mDrawingRect.right,bottom=mDrawingRect.bottom;
mProgressRect=new RectF(left,top,(mProgressPercent/100)*right,bottom);
canvas.drawRoundRect(mProgressRect, x_Corner, y_Corner, mRectPaintPrimary);
//noinspection ResourceType
String newColor = getResources().getString(mRectPaintPrimary.getColor());
Log.d(TAG,"Rect colour while drawing is "+newColor);
String valueString=((int)mProgressPercent)+"%";
if(mProgressPercent<10)
valueString="";
canvas.drawText(valueString,mProgressRect.centerX(),mProgressRect.centerY()*1.5f,mRegularText);
}
My log actually says that programatically the colour has been modified. So I get a message on the lines of
D/GaugeView: Rect colour while drawing is #ffe64a19
But what I see on the android display is always the same grey...no matter how what I change the colour to be:
回答1:
I seem to have got my required result by changing
mRectPaintPrimary.setColor(mPrimaryColor);
to
mRectPaintPrimary.setColor(getResources().getColor(mPrimaryColor));
Or even better
mRectPaintPrimary.setColor(ContextCompat.getColor(mContext,mPrimaryColor));
来源:https://stackoverflow.com/questions/39820240/android-canvas-drawrect-colour-always-shows-as-grey