Android Tutorial - 2D Graphics : Color
Using solid color to paint
package app.Test; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Path.Direction; import android.os.Bundle; import android.view.View; public class appTest extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(new GraphicsView(this)); } static public class GraphicsView extends View { private static final String QUOTE = "This is a test. This is a demo."; private Path circle; private Paint cPaint; private Paint tPaint; public GraphicsView(Context context) { super(context); int color = Color.BLUE; circle = new Path(); circle.addCircle(150, 150, 100, Direction.CW); cPaint = new Paint(Paint.ANTI_ALIAS_FLAG); cPaint.setStyle(Paint.Style.STROKE); cPaint.setColor(Color.LTGRAY); cPaint.setStrokeWidth(3); setBackgroundResource(R.drawable.icon); } @Override protected void onDraw(Canvas canvas) { canvas.drawPath(circle, cPaint); } } } //main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/icon"> <org.example.graphics.Graphics.GraphicsView android:id="@+id/graphics" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout> //strings.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Graphics</string> </resources> //colors.xml <?xml version="1.0" encoding="utf-8"?> <resources> <color name="mycolor">#7fff00ff</color> </resources>
Set color for Paint
package app.test; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Typeface; import android.os.Bundle; import android.widget.ImageView; public class Test extends Activity { ImageView drawingImageView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); drawingImageView = (ImageView) this.findViewById(R.id.DrawingImageView); Bitmap bitmap = Bitmap.createBitmap((int) getWindowManager() .getDefaultDisplay().getWidth(), (int) getWindowManager() .getDefaultDisplay().getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawingImageView.setImageBitmap(bitmap); Paint paint = new Paint(); paint.setColor(Color.GREEN); paint.setStrokeWidth(100); canvas.drawPoint(199, 201, paint); } }
Create Color from RGB value
package app.Test; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Path.Direction; import android.os.Bundle; import android.view.View; public class appTest extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(new GraphicsView(this)); } static public class GraphicsView extends View { private static final String QUOTE = "This is a test. This is a demo."; private Path circle; private Paint cPaint; private Paint tPaint; public GraphicsView(Context context) { super(context); int color = Color.argb(127, 255, 0, 255); circle = new Path(); circle.addCircle(150, 150, 100, Direction.CW); cPaint = new Paint(Paint.ANTI_ALIAS_FLAG); cPaint.setStyle(Paint.Style.STROKE); cPaint.setColor(Color.LTGRAY); cPaint.setStrokeWidth(3); setBackgroundResource(R.drawable.icon); } @Override protected void onDraw(Canvas canvas) { canvas.drawPath(circle, cPaint); } } } //main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/icon"> <org.example.graphics.Graphics.GraphicsView android:id="@+id/graphics" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout> //strings.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Graphics</string> </resources> //colors.xml <?xml version="1.0" encoding="utf-8"?> <resources> <color name="mycolor">#7fff00ff</color> </resources>
Load Color from resource xml file
package app.Test; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Path.Direction; import android.os.Bundle; import android.view.View; public class appTest extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(new GraphicsView(this)); } static public class GraphicsView extends View { private static final String QUOTE = "This is a test. This is a demo."; private Path circle; private Paint cPaint; private Paint tPaint; public GraphicsView(Context context) { super(context); int color = getResources().getColor(R.color.mycolor); circle = new Path(); circle.addCircle(150, 150, 100, Direction.CW); cPaint = new Paint(Paint.ANTI_ALIAS_FLAG); cPaint.setStyle(Paint.Style.STROKE); cPaint.setColor(Color.LTGRAY); cPaint.setStrokeWidth(3); setBackgroundResource(R.drawable.icon); tPaint = new Paint(Paint.ANTI_ALIAS_FLAG); tPaint.setStyle(Paint.Style.FILL_AND_STROKE); tPaint.setColor(Color.BLACK); tPaint.setTextSize(20f); setBackgroundColor(color); } @Override protected void onDraw(Canvas canvas) { canvas.drawTextOnPath(QUOTE, circle, 0, 20, tPaint); } } } //main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/icon"> <org.example.graphics.Graphics.GraphicsView android:id="@+id/graphics" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout> //strings.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Graphics</string> </resources> //colors.xml <?xml version="1.0" encoding="utf-8"?> <resources> <color name="mycolor">#7fff00ff</color> </resources>
Using View to display color
package app.test; import android.app.Activity; import android.os.Bundle; public class Test extends Activity { @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); } } <?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content"> <TableLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:stretchColumns="0"> <TableRow> <View android:layout_height="80px" android:background="#000000"/> <TextView android:text="#000000" android:paddingLeft="4px" android:layout_gravity="center_vertical" /> </TableRow> <TableRow> <View android:layout_height="80px" android:background="#440000" /> <TextView android:text="#440000" android:paddingLeft="4px" android:layout_gravity="center_vertical" /> </TableRow> <TableRow> <View android:layout_height="80px" android:background="#884400" /> <TextView android:text="#884400" android:paddingLeft="4px" android:layout_gravity="center_vertical" /> </TableRow> <TableRow> <View android:layout_height="80px" android:background="#aa8844" /> <TextView android:text="#aa8844" android:paddingLeft="4px" android:layout_gravity="center_vertical" /> </TableRow> <TableRow> <View android:layout_height="80px" android:background="#ffaa88" /> <TextView android:text="#ffaa88" android:paddingLeft="4px" android:layout_gravity="center_vertical" /> </TableRow> <TableRow> <View android:layout_height="80px" android:background="#ffffaa" /> <TextView android:text="#ffffaa" android:paddingLeft="4px" android:layout_gravity="center_vertical" /> </TableRow> <TableRow> <View android:layout_height="80px" android:background="#ffffff" /> <TextView android:text="#ffffff" android:paddingLeft="4px" android:layout_gravity="center_vertical" /> </TableRow> </TableLayout> </ScrollView>
Change check box color
package app.test; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.CheckBox; public class Test extends Activity { @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); final CheckBox checkbox = (CheckBox) findViewById(R.id.testCheckBox); final Button changeButton = (Button) findViewById(R.id.layoutButton); changeButton.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { changeOption(checkbox); } }); final Button changeButton2 = (Button) findViewById(R.id.textColorButton); changeButton2.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { changeOption2(checkbox); } }); } public void changeOption(CheckBox checkbox) { if (checkbox.getHeight() == 100) { checkbox.setHeight(30); } else { checkbox.setHeight(100); } } public void changeOption2(CheckBox checkbox) { checkbox.setTextColor(Color.RED); } } //main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <CheckBox android:id="@+id/testCheckBox" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="This is the test CheckBox"/> <Button android:id="@+id/layoutButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Change Layout"/> <Button android:id="@+id/textColorButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Change Text Color"/> </LinearLayout>
Color Filters
package app.test; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Paint; import android.graphics.Picture; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; public class Test extends GraphicsActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(new SampleView(this)); } private static class SampleView extends View { private Activity mActivity; private Drawable mDrawable; private Drawable[] mDrawables; private Paint mPaint; private Paint mPaint2; private float mPaintTextOffset; private int[] mColors; private PorterDuff.Mode[] mModes; private int mModeIndex; private static void addToTheRight(Drawable curr, Drawable prev) { Rect r = prev.getBounds(); int x = r.right + 12; int center = (r.top + r.bottom) >> 1; int h = curr.getIntrinsicHeight(); int y = center - (h >> 1); curr.setBounds(x, y, x + curr.getIntrinsicWidth(), y + h); } public SampleView(Activity activity) { super(activity); mActivity = activity; Context context = activity; setFocusable(true); mDrawable = context.getResources().getDrawable( R.drawable.icon); mDrawable.setBounds(0, 0, 150, 48); mDrawable.setDither(true); int[] resIDs = new int[] { R.drawable.icon,R.drawable.icon, R.drawable.icon}; mDrawables = new Drawable[resIDs.length]; Drawable prev = mDrawable; for (int i = 0; i < resIDs.length; i++) { mDrawables[i] = context.getResources().getDrawable(resIDs[i]); mDrawables[i].setDither(true); addToTheRight(mDrawables[i], prev); prev = mDrawables[i]; } mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setTextSize(16); mPaint.setTextAlign(Paint.Align.CENTER); mPaint2 = new Paint(mPaint); mPaint2.setAlpha(64); Paint.FontMetrics fm = mPaint.getFontMetrics(); mPaintTextOffset = (fm.descent + fm.ascent) * 0.5f; mColors = new int[] { 0, 0xCC0000FF, 0x880000FF, 0x440000FF, 0xFFCCCCFF, 0xFF8888FF, 0xFF4444FF, }; mModes = new PorterDuff.Mode[] { PorterDuff.Mode.SRC_ATOP, PorterDuff.Mode.MULTIPLY, }; mModeIndex = 0; updateTitle(); } private void swapPaintColors() { if (mPaint.getColor() == 0xFF000000) { mPaint.setColor(0xFFFFFFFF); mPaint2.setColor(0xFF000000); } else { mPaint.setColor(0xFF000000); mPaint2.setColor(0xFFFFFFFF); } mPaint2.setAlpha(64); } private void updateTitle() { mActivity.setTitle(mModes[mModeIndex].toString()); } private void drawSample(Canvas canvas, ColorFilter filter) { Rect r = mDrawable.getBounds(); float x = (r.left + r.right) * 0.5f; float y = (r.top + r.bottom) * 0.5f - mPaintTextOffset; mDrawable.setColorFilter(filter); mDrawable.draw(canvas); canvas.drawText("Label", x + 1, y + 1, mPaint2); canvas.drawText("Label", x, y, mPaint); for (Drawable dr : mDrawables) { dr.setColorFilter(filter); dr.draw(canvas); } } @Override protected void onDraw(Canvas canvas) { canvas.drawColor(0xFFCCCCCC); canvas.translate(8, 12); for (int color : mColors) { ColorFilter filter; if (color == 0) { filter = null; } else { filter = new PorterDuffColorFilter(color, mModes[mModeIndex]); } drawSample(canvas, filter); canvas.translate(0, 55); } } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: break; case MotionEvent.ACTION_MOVE: break; case MotionEvent.ACTION_UP: // update mode every other time we change paint colors if (mPaint.getColor() == 0xFFFFFFFF) { mModeIndex = (mModeIndex + 1) % mModes.length; updateTitle(); } swapPaintColors(); invalidate(); break; } return true; } } } class GraphicsActivity extends Activity { // set to true to test Picture private static final boolean TEST_PICTURE = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void setContentView(View view) { if (TEST_PICTURE) { ViewGroup vg = new PictureLayout(this); vg.addView(view); view = vg; } super.setContentView(view); } } class PictureLayout extends ViewGroup { private final Picture mPicture = new Picture(); public PictureLayout(Context context) { super(context); } public PictureLayout(Context context, AttributeSet attrs) { super(context, attrs); } @Override public void addView(View child) { if (getChildCount() > 1) { throw new IllegalStateException( "PictureLayout can host only one direct child"); } super.addView(child); } @Override public void addView(View child, int index) { if (getChildCount() > 1) { throw new IllegalStateException( "PictureLayout can host only one direct child"); } super.addView(child, index); } @Override public void addView(View child, LayoutParams params) { if (getChildCount() > 1) { throw new IllegalStateException( "PictureLayout can host only one direct child"); } super.addView(child, params); } @Override public void addView(View child, int index, LayoutParams params) { if (getChildCount() > 1) { throw new IllegalStateException( "PictureLayout can host only one direct child"); } super.addView(child, index, params); } @Override protected LayoutParams generateDefaultLayoutParams() { return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int count = getChildCount(); int maxHeight = 0; int maxWidth = 0; for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { measureChild(child, widthMeasureSpec, heightMeasureSpec); } } maxWidth += getPaddingLeft() + getPaddingRight(); maxHeight += getPaddingTop() + getPaddingBottom(); Drawable drawable = getBackground(); if (drawable != null) { maxHeight = Math.max(maxHeight, drawable.getMinimumHeight()); maxWidth = Math.max(maxWidth, drawable.getMinimumWidth()); } setMeasuredDimension(resolveSize(maxWidth, widthMeasureSpec), resolveSize(maxHeight, heightMeasureSpec)); } private void drawPict(Canvas canvas, int x, int y, int w, int h, float sx, float sy) { canvas.save(); canvas.translate(x, y); canvas.clipRect(0, 0, w, h); canvas.scale(0.5f, 0.5f); canvas.scale(sx, sy, w, h); canvas.drawPicture(mPicture); canvas.restore(); } @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(mPicture.beginRecording(getWidth(), getHeight())); mPicture.endRecording(); int x = getWidth() / 2; int y = getHeight() / 2; if (false) { canvas.drawPicture(mPicture); } else { drawPict(canvas, 0, 0, x, y, 1, 1); drawPict(canvas, x, 0, x, y, -1, 1); drawPict(canvas, 0, y, x, y, 1, -1); drawPict(canvas, x, y, x, y, -1, -1); } } @Override public ViewParent invalidateChildInParent(int[] location, Rect dirty) { location[0] = getLeft(); location[1] = getTop(); dirty.set(0, 0, getWidth(), getHeight()); return getParent(); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int count = super.getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { final int childLeft = getPaddingLeft(); final int childTop = getPaddingTop(); child.layout(childLeft, childTop, childLeft + child.getMeasuredWidth(), childTop + child.getMeasuredHeight()); } } } }
Color Matrix Sample
package app.test; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; import android.graphics.Paint; import android.graphics.Picture; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; public class Test extends GraphicsActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(new SampleView(this)); } private static class SampleView extends View { private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private Bitmap mBitmap; private float mAngle; public SampleView(Context context) { super(context); mBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon); } private static void setTranslate(ColorMatrix cm, float dr, float dg, float db, float da) { cm.set(new float[] { 2, 0, 0, 0, dr, 0, 2, 0, 0, dg, 0, 0, 2, 0, db, 0, 0, 0, 1, da }); } private static void setContrast(ColorMatrix cm, float contrast) { float scale = contrast + 1.f; float translate = (-.5f * scale + .5f) * 255.f; cm.set(new float[] { scale, 0, 0, 0, translate, 0, scale, 0, 0, translate, 0, 0, scale, 0, translate, 0, 0, 0, 1, 0 }); } private static void setContrastTranslateOnly(ColorMatrix cm, float contrast) { float scale = contrast + 1.f; float translate = (-.5f * scale + .5f) * 255.f; cm.set(new float[] { 1, 0, 0, 0, translate, 0, 1, 0, 0, translate, 0, 0, 1, 0, translate, 0, 0, 0, 1, 0 }); } private static void setContrastScaleOnly(ColorMatrix cm, float contrast) { float scale = contrast + 1.f; float translate = (-.5f * scale + .5f) * 255.f; cm.set(new float[] { scale, 0, 0, 0, 0, 0, scale, 0, 0, 0, 0, 0, scale, 0, 0, 0, 0, 0, 1, 0 }); } @Override protected void onDraw(Canvas canvas) { Paint paint = mPaint; float x = 20; float y = 20; canvas.drawColor(Color.WHITE); paint.setColorFilter(null); canvas.drawBitmap(mBitmap, x, y, paint); ColorMatrix cm = new ColorMatrix(); mAngle += 2; if (mAngle > 180) { mAngle = 0; } // convert our animated angle [-180...180] to a contrast value of // [-1..1] float contrast = mAngle / 180.f; setContrast(cm, contrast); paint.setColorFilter(new ColorMatrixColorFilter(cm)); canvas.drawBitmap(mBitmap, x + mBitmap.getWidth() + 10, y, paint); setContrastScaleOnly(cm, contrast); paint.setColorFilter(new ColorMatrixColorFilter(cm)); canvas.drawBitmap(mBitmap, x, y + mBitmap.getHeight() + 10, paint); setContrastTranslateOnly(cm, contrast); paint.setColorFilter(new ColorMatrixColorFilter(cm)); canvas.drawBitmap(mBitmap, x, y + 2 * (mBitmap.getHeight() + 10), paint); invalidate(); } } } class GraphicsActivity extends Activity { // set to true to test Picture private static final boolean TEST_PICTURE = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void setContentView(View view) { if (TEST_PICTURE) { ViewGroup vg = new PictureLayout(this); vg.addView(view); view = vg; } super.setContentView(view); } } class PictureLayout extends ViewGroup { private final Picture mPicture = new Picture(); public PictureLayout(Context context) { super(context); } public PictureLayout(Context context, AttributeSet attrs) { super(context, attrs); } @Override public void addView(View child) { if (getChildCount() > 1) { throw new IllegalStateException( "PictureLayout can host only one direct child"); } super.addView(child); } @Override public void addView(View child, int index) { if (getChildCount() > 1) { throw new IllegalStateException( "PictureLayout can host only one direct child"); } super.addView(child, index); } @Override public void addView(View child, LayoutParams params) { if (getChildCount() > 1) { throw new IllegalStateException( "PictureLayout can host only one direct child"); } super.addView(child, params); } @Override public void addView(View child, int index, LayoutParams params) { if (getChildCount() > 1) { throw new IllegalStateException( "PictureLayout can host only one direct child"); } super.addView(child, index, params); } @Override protected LayoutParams generateDefaultLayoutParams() { return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int count = getChildCount(); int maxHeight = 0; int maxWidth = 0; for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { measureChild(child, widthMeasureSpec, heightMeasureSpec); } } maxWidth += getPaddingLeft() + getPaddingRight(); maxHeight += getPaddingTop() + getPaddingBottom(); Drawable drawable = getBackground(); if (drawable != null) { maxHeight = Math.max(maxHeight, drawable.getMinimumHeight()); maxWidth = Math.max(maxWidth, drawable.getMinimumWidth()); } setMeasuredDimension(resolveSize(maxWidth, widthMeasureSpec), resolveSize(maxHeight, heightMeasureSpec)); } private void drawPict(Canvas canvas, int x, int y, int w, int h, float sx, float sy) { canvas.save(); canvas.translate(x, y); canvas.clipRect(0, 0, w, h); canvas.scale(0.5f, 0.5f); canvas.scale(sx, sy, w, h); canvas.drawPicture(mPicture); canvas.restore(); } @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(mPicture.beginRecording(getWidth(), getHeight())); mPicture.endRecording(); int x = getWidth() / 2; int y = getHeight() / 2; if (false) { canvas.drawPicture(mPicture); } else { drawPict(canvas, 0, 0, x, y, 1, 1); drawPict(canvas, x, 0, x, y, -1, 1); drawPict(canvas, 0, y, x, y, 1, -1); drawPict(canvas, x, y, x, y, -1, -1); } } @Override public ViewParent invalidateChildInParent(int[] location, Rect dirty) { location[0] = getLeft(); location[1] = getTop(); dirty.set(0, 0, getWidth(), getHeight()); return getParent(); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int count = super.getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { final int childLeft = getPaddingLeft(); final int childTop = getPaddingTop(); child.layout(childLeft, childTop, childLeft + child.getMeasuredWidth(), childTop + child.getMeasuredHeight()); } } } }
HSV To Color
import android.graphics.Color; public class ColorUtils { // // Constants // private static final float[] HSV_TO_COLOR = new float[3]; private static final int HSV_TO_COLOR_HUE_INDEX = 0; private static final int HSV_TO_COLOR_SATURATION_INDEX = 1; private static final int HSV_TO_COLOR_VALUE_INDEX = 2; private static final int COLOR_FLOAT_TO_INT_FACTOR = 255; public static int HSVToColor(final float pHue, final float pSaturation, final float pValue) { HSV_TO_COLOR[HSV_TO_COLOR_HUE_INDEX] = pHue; HSV_TO_COLOR[HSV_TO_COLOR_SATURATION_INDEX] = pSaturation; HSV_TO_COLOR[HSV_TO_COLOR_VALUE_INDEX] = pValue; return Color.HSVToColor(HSV_TO_COLOR); } public static int RGBToColor(final float pRed, final float pGreen, final float pBlue) { return Color.rgb((int)(pRed * COLOR_FLOAT_TO_INT_FACTOR), (int)(pGreen * COLOR_FLOAT_TO_INT_FACTOR), (int)(pBlue * COLOR_FLOAT_TO_INT_FACTOR)); } }
RGB To Color
//package org.anddev.andengine.util; import android.graphics.Color; public class ColorUtils { private static final float[] HSV_TO_COLOR = new float[3]; private static final int HSV_TO_COLOR_HUE_INDEX = 0; private static final int HSV_TO_COLOR_SATURATION_INDEX = 1; private static final int HSV_TO_COLOR_VALUE_INDEX = 2; private static final int COLOR_FLOAT_TO_INT_FACTOR = 255; public static int HSVToColor(final float pHue, final float pSaturation, final float pValue) { HSV_TO_COLOR[HSV_TO_COLOR_HUE_INDEX] = pHue; HSV_TO_COLOR[HSV_TO_COLOR_SATURATION_INDEX] = pSaturation; HSV_TO_COLOR[HSV_TO_COLOR_VALUE_INDEX] = pValue; return Color.HSVToColor(HSV_TO_COLOR); } public static int RGBToColor(final float pRed, final float pGreen, final float pBlue) { return Color.rgb((int)(pRed * COLOR_FLOAT_TO_INT_FACTOR), (int)(pGreen * COLOR_FLOAT_TO_INT_FACTOR), (int)(pBlue * COLOR_FLOAT_TO_INT_FACTOR)); } }
lighten Color
import android.graphics.Color; class Util { public static int lightenColor(int color,float factor){ float r = Color.red(color)*factor; float g = Color.green(color)*factor; float b = Color.blue(color)*factor; int ir = Math.min(255,(int)r); int ig = Math.min(255,(int)g); int ib = Math.min(255,(int)b); int ia = Color.alpha(color); return(Color.argb(ia, ir, ig, ib)); } }
Get Random Location and Colors
import java.util.Vector; import android.graphics.Color; import android.graphics.Point; import android.graphics.Rect; class ShakeUtil { public static Vector<Point> getRandomLocations(Rect dimensions,int count) { Vector<Point> randoms=new Vector<Point>(count); for (int i=0;i<count;i++) { int width=dimensions.right-dimensions.left; int height=dimensions.bottom-dimensions.top; int x=(int) (dimensions.left+(Math.round(width*Math.random()))); int y=(int) (dimensions.top+(Math.round(height*Math.random()))); randoms.add(new Point(x,y)); } return randoms; } public static Vector<Integer> getRandomColors(int count) { String[] barvy={"red", "blue", "green", "gray", "cyan", "magenta", "lightgray", "darkgray"}; Vector<Integer> randoms=new Vector<Integer>(count); for (int i=0;i<count;i++) { int c=Color.parseColor(barvy[(int) Math.round((barvy.length-1)*Math.random())]); randoms.add(Integer.valueOf(c)); } return randoms; } }
Returns the complimentary (opposite) color.
//package mobilesmil.utils; import android.graphics.Color; import android.graphics.Paint; public class ColorUtils { public static int getComplimentColor(Paint paint) { return getComplimentColor(paint.getColor()); } public static int getComplimentColor(int color) { // get existing colors int alpha = Color.alpha(color); int red = Color.red(color); int blue = Color.blue(color); int green = Color.green(color); // find compliments red = (~red) & 0xff; blue = (~blue) & 0xff; green = (~green) & 0xff; return Color.argb(alpha, red, green, blue); } public static String getHexStringForARGB(int argbColor) { String hexString = "#"; hexString += ARGBToHex(Color.alpha(argbColor)); hexString += ARGBToHex(Color.red(argbColor)); hexString += ARGBToHex(Color.green(argbColor)); hexString += ARGBToHex(Color.blue(argbColor)); return hexString; } private static String ARGBToHex(int rgbVal) { String hexReference = "0123456789ABCDEF"; rgbVal = Math.max(0,rgbVal); rgbVal = Math.min(rgbVal,255); rgbVal = Math.round(rgbVal); return String.valueOf( hexReference.charAt((rgbVal-rgbVal%16)/16) + "" + hexReference.charAt(rgbVal%16) ); } }
brighter a color
import android.graphics.Color; class Main { public static int brighter(int c) { int r = Color.red(c); int b = Color.blue(c); int g = Color.green(c); if (r == 0 && b == 0 && g == 0) { return Color.DKGRAY; } if (r < 3 && r != 0) { r = 3; } else { r = (int) (r / .7); r = (r > 255) ? 255 : r; } if (b < 3 && b != 0) { b = 3; } else { b = (int) (b / .7); b = (b > 255) ? 255 : b; } if (g < 3 && g != 0) { g = 3; } else { g = (int) (g / .7); g = (g > 255) ? 255 : g; } return Color.rgb(r, g, b); } }
darker a color
import android.graphics.Color; class Main { public static int darker(int c) { int r = Color.red(c); int b = Color.blue(c); int g = Color.green(c); return Color.rgb((int)(r*.7), (int)(g*.7), (int)(b*.7)); } }
extends View to create ColorCircle
//package org.openintents.widget; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PointF; import android.graphics.Shader; import android.graphics.SweepGradient; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; /** * Interface for notifications of position change of slider. * * @author Peli */ interface OnColorChangedListener { /** * This method is called when the user changed the color. * * This works in touch mode, by dragging the along the * color circle with the finger. */ void onColorChanged(View view, int newColor); /** * This method is called when the user clicks the center button. * * @param colorcircle * @param newColor */ void onColorPicked(View view, int newColor); } /** * ColorCircle. * * @author Peli, based on API demo code. * */ public class ColorCircle extends View { private float center_radius; private final static float CENTER_RADIUS_SCALE = 0.4f; private Paint mPaint; private Paint mCenterPaint; private int[] mColors; private OnColorChangedListener mListener; /** * Constructor. This version is only needed for instantiating the object * manually (not from a layout XML file). * * @param context */ public ColorCircle(Context context) { super(context); init(); } /** * Construct object, initializing with any attributes we understand from a * layout file. * * These attributes are defined in res/values/attrs.xml . * * @see android.view.View#View(android.content.Context, * android.util.AttributeSet, java.util.Map) */ public ColorCircle(Context context, AttributeSet attrs) { super(context, attrs); // TODO what happens with inflateParams init(); } /** * Initializes variables. */ void init() { mColors = new int[] { 0xFFFF0000, 0xFFFF00FF, 0xFF0000FF, 0xFF00FFFF, 0xFF00FF00, 0xFFFFFF00, 0xFFFF0000 }; Shader s = new SweepGradient(0, 0, mColors, null); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaint.setShader(s); mPaint.setStyle(Paint.Style.STROKE); mCenterPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mCenterPaint.setStrokeWidth(5); } private boolean mTrackingCenter; private boolean mHighlightCenter; @Override protected void onDraw(Canvas canvas) { float outer_radius = Math.min(getWidth(), getHeight())/2; float touch_feedback_ring = center_radius + 2*mCenterPaint.getStrokeWidth(); float r = (outer_radius + touch_feedback_ring) / 2; canvas.translate(getWidth()/2, getHeight()/2); mPaint.setStrokeWidth(outer_radius - touch_feedback_ring); // This is the main "color ring" canvas.drawCircle(0, 0, r, mPaint); // This is the center "activation button" circle canvas.drawCircle(0, 0, center_radius, mCenterPaint); if (mTrackingCenter) { int c = mCenterPaint.getColor(); mCenterPaint.setStyle(Paint.Style.STROKE); if (mHighlightCenter) { mCenterPaint.setAlpha(0xFF); } else { mCenterPaint.setAlpha(0x80); } // The skinny ring around the center to indicate that it is being pressed canvas.drawCircle(0, 0, center_radius + mCenterPaint.getStrokeWidth(), mCenterPaint); mCenterPaint.setStyle(Paint.Style.FILL); mCenterPaint.setColor(c); } } /** * @see android.view.View#measure(int, int) */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int max_width = MeasureSpec.getSize(widthMeasureSpec); int max_height = MeasureSpec.getSize(heightMeasureSpec); int size = Math.min(max_width, max_height); this.center_radius = CENTER_RADIUS_SCALE * size/2; setMeasuredDimension(size, size); } public void setColor(int color) { mCenterPaint.setColor(color); invalidate(); } public int getColor() { return mCenterPaint.getColor(); } public void setOnColorChangedListener( OnColorChangedListener colorListener) { mListener = colorListener; } private int ave(int s, int d, float p) { return s + java.lang.Math.round(p * (d - s)); } private int interpColor(int colors[], float unit) { if (unit <= 0) { return colors[0]; } if (unit >= 1) { return colors[colors.length - 1]; } float p = unit * (colors.length - 1); int i = (int)p; p -= i; // now p is just the fractional part [0...1) and i is the index int c0 = colors[i]; int c1 = colors[i+1]; int a = ave(Color.alpha(c0), Color.alpha(c1), p); int r = ave(Color.red(c0), Color.red(c1), p); int g = ave(Color.green(c0), Color.green(c1), p); int b = ave(Color.blue(c0), Color.blue(c1), p); return Color.argb(a, r, g, b); } @Override public boolean onTouchEvent(MotionEvent event) { float x = event.getX() - getWidth()/2; float y = event.getY() - getHeight()/2; boolean inCenter = PointF.length(x, y) <= center_radius; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mTrackingCenter = inCenter; if (inCenter) { mHighlightCenter = true; invalidate(); break; } case MotionEvent.ACTION_MOVE: if (mTrackingCenter) { if (mHighlightCenter != inCenter) { mHighlightCenter = inCenter; invalidate(); } } else { float angle = (float)java.lang.Math.atan2(y, x); // need to turn angle [-PI ... PI] into unit [0....1] float unit = angle/(2*(float) Math.PI); if (unit < 0) { unit += 1; } int newcolor = interpColor(mColors, unit); mCenterPaint.setColor(newcolor); if (mListener != null) { mListener.onColorChanged(this, newcolor); } invalidate(); } break; case MotionEvent.ACTION_UP: if (mTrackingCenter) { if (inCenter) { if (mListener != null) { mListener.onColorPicked(this, mCenterPaint.getColor()); } } mTrackingCenter = false; // so we draw w/o halo invalidate(); } break; } return true; } }
Increase Red
package app.test; import java.io.FileNotFoundException; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; import android.graphics.Matrix; import android.graphics.Paint; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.Display; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; public class Test extends Activity implements OnClickListener { ImageView chosenImageView; Button choosePicture; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); chosenImageView = (ImageView) this.findViewById(R.id.ChosenImageView); choosePicture = (Button) this.findViewById(R.id.ChoosePictureButton); choosePicture.setOnClickListener(this); } public void onClick(View v) { Intent choosePictureIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(choosePictureIntent, 0); } protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (resultCode == RESULT_OK) { Uri imageFileUri = intent.getData(); Display currentDisplay = getWindowManager().getDefaultDisplay(); int dw = currentDisplay.getWidth(); int dh = currentDisplay.getHeight() / 2 - 100; try { BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options(); bmpFactoryOptions.inJustDecodeBounds = true; Bitmap bmp = BitmapFactory .decodeStream(getContentResolver().openInputStream( imageFileUri), null, bmpFactoryOptions); int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight / (float) dh); int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth / (float) dw); if (heightRatio > 1 && widthRatio > 1) { if (heightRatio > widthRatio) { bmpFactoryOptions.inSampleSize = heightRatio; } else { bmpFactoryOptions.inSampleSize = widthRatio; } } bmpFactoryOptions.inJustDecodeBounds = false; bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageFileUri), null, bmpFactoryOptions); Bitmap alteredBitmap = Bitmap.createBitmap(bmp.getWidth(), bmp .getHeight(), bmp.getConfig()); Canvas canvas = new Canvas(alteredBitmap); Paint paint = new Paint(); ColorMatrix cm = new ColorMatrix(); // Increase Red cm.set(new float[] { 2, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0 }); paint.setColorFilter(new ColorMatrixColorFilter(cm)); Matrix matrix = new Matrix(); canvas.drawBitmap(bmp, matrix, paint); ImageView alteredImageView = (ImageView) this .findViewById(R.id.AlteredImageView); alteredImageView.setImageBitmap(alteredBitmap); chosenImageView.setImageBitmap(bmp); } catch (Exception e) { Log.v("ERROR", e.toString()); } } } } //main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Choose Picture" android:id="@+id/ChoosePictureButton"/> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/ChosenImageView"></ImageView> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/AlteredImageView"></ImageView> </LinearLayout>
ncrease Contrast, Reduce Brightness
package app.test; import java.io.FileNotFoundException; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; import android.graphics.Matrix; import android.graphics.Paint; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.Display; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; public class Test extends Activity implements OnClickListener { ImageView chosenImageView; Button choosePicture; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); chosenImageView = (ImageView) this.findViewById(R.id.ChosenImageView); choosePicture = (Button) this.findViewById(R.id.ChoosePictureButton); choosePicture.setOnClickListener(this); } public void onClick(View v) { Intent choosePictureIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(choosePictureIntent, 0); } protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (resultCode == RESULT_OK) { Uri imageFileUri = intent.getData(); Display currentDisplay = getWindowManager().getDefaultDisplay(); int dw = currentDisplay.getWidth(); int dh = currentDisplay.getHeight() / 2 - 100; try { BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options(); bmpFactoryOptions.inJustDecodeBounds = true; Bitmap bmp = BitmapFactory .decodeStream(getContentResolver().openInputStream( imageFileUri), null, bmpFactoryOptions); int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight / (float) dh); int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth / (float) dw); if (heightRatio > 1 && widthRatio > 1) { if (heightRatio > widthRatio) { bmpFactoryOptions.inSampleSize = heightRatio; } else { bmpFactoryOptions.inSampleSize = widthRatio; } } bmpFactoryOptions.inJustDecodeBounds = false; bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageFileUri), null, bmpFactoryOptions); Bitmap alteredBitmap = Bitmap.createBitmap(bmp.getWidth(), bmp .getHeight(), bmp.getConfig()); Canvas canvas = new Canvas(alteredBitmap); Paint paint = new Paint(); ColorMatrix cm = new ColorMatrix(); // Increase Contrast, Slightly Reduce Brightness float contrast = 3; float brightness = -5; cm.set(new float[] { contrast, 0, 0, 0, brightness, 0, contrast, 0, 0, brightness, 0, 0, contrast, 0, brightness, 0, 0, 0, 1, 0 }); paint.setColorFilter(new ColorMatrixColorFilter(cm)); Matrix matrix = new Matrix(); canvas.drawBitmap(bmp, matrix, paint); ImageView alteredImageView = (ImageView) this .findViewById(R.id.AlteredImageView); alteredImageView.setImageBitmap(alteredBitmap); chosenImageView.setImageBitmap(bmp); } catch (Exception e) { Log.v("ERROR", e.toString()); } } } } //main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Choose Picture" android:id="@+id/ChoosePictureButton"/> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/ChosenImageView"></ImageView> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/AlteredImageView"></ImageView> </LinearLayout>
Decrease Saturation
package app.test;
import java.io.FileNotFoundException;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class Test extends Activity implements OnClickListener {
ImageView chosenImageView;
Button choosePicture;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
chosenImageView = (ImageView) this.findViewById(R.id.ChosenImageView);
choosePicture = (Button) this.findViewById(R.id.ChoosePictureButton);
choosePicture.setOnClickListener(this);
}
public void onClick(View v) {
Intent choosePictureIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(choosePictureIntent, 0);
}
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_OK) {
Uri imageFileUri = intent.getData();
Display currentDisplay = getWindowManager().getDefaultDisplay();
int dw = currentDisplay.getWidth();
int dh = currentDisplay.getHeight() / 2 - 100;
try {
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory
.decodeStream(getContentResolver().openInputStream(
imageFileUri), null, bmpFactoryOptions);
int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight
/ (float) dh);
int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth
/ (float) dw);
if (heightRatio > 1 && widthRatio > 1) {
if (heightRatio > widthRatio) {
bmpFactoryOptions.inSampleSize = heightRatio;
} else {
bmpFactoryOptions.inSampleSize = widthRatio;
}
}
bmpFactoryOptions.inJustDecodeBounds = false;
bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageFileUri), null, bmpFactoryOptions);
Bitmap alteredBitmap = Bitmap.createBitmap(bmp.getWidth(), bmp
.getHeight(), bmp.getConfig());
Canvas canvas = new Canvas(alteredBitmap);
Paint paint = new Paint();
ColorMatrix cm = new ColorMatrix();
// Decrease Saturation
cm.setSaturation(.5f);
paint.setColorFilter(new ColorMatrixColorFilter(cm));
Matrix matrix = new Matrix();
canvas.drawBitmap(bmp, matrix, paint);
ImageView alteredImageView = (ImageView) this
.findViewById(R.id.AlteredImageView);
alteredImageView.setImageBitmap(alteredBitmap);
chosenImageView.setImageBitmap(bmp);
} catch (Exception e) {
Log.v("ERROR", e.toString());
}
}
}
}
//main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Choose Picture" android:id="@+id/ChoosePictureButton"/>
<ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/ChosenImageView"></ImageView>
<ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/AlteredImageView"></ImageView>
</LinearLayout>