Example usage for android.graphics Color colorToHSV

List of usage examples for android.graphics Color colorToHSV

Introduction

In this page you can find the example usage for android.graphics Color colorToHSV.

Prototype

public static void colorToHSV(@ColorInt int color, @Size(3) float hsv[]) 

Source Link

Document

Convert the ARGB color to its HSV components.

Usage

From source file:com.derrick.movies.MovieDetailsActivity.java

private void loadPoster(Context baseContext, String url, final ImageView image) {
    Glide.with(baseContext).load(IMAGE_BASE + url).diskCacheStrategy(DiskCacheStrategy.ALL)
            .listener(new RequestListener<String, GlideDrawable>() {
                @Override//from w ww. ja v a 2s .  co m
                public boolean onException(Exception e, String model, Target<GlideDrawable> target,
                        boolean isFirstResource) {
                    return false;
                }

                @Override
                public boolean onResourceReady(GlideDrawable resource, String model,
                        Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                    Bitmap bitmap = ((GlideBitmapDrawable) resource).getBitmap();
                    if (bitmap != null) {
                        Palette.from(bitmap).maximumColorCount(24).generate(new Palette.PaletteAsyncListener() {
                            @Override
                            public void onGenerated(Palette palette) {

                                int vibrantColor = palette
                                        .getVibrantColor(getResources().getColor(R.color.colorPrimary));
                                float[] hsv = new float[3];
                                Color.colorToHSV(vibrantColor, hsv);
                                hsv[2] *= 0.8f;
                                int darkerColor = Color.HSVToColor(hsv);
                                toolbarLayout.setContentScrimColor(vibrantColor);
                                toolbarLayout.setStatusBarScrimColor(darkerColor);
                                setStatusBarColor(darkerColor);
                                TagLineLayout.setBackgroundColor(vibrantColor);
                                //imageBackdrop.setColorFilter(new ColorMatrixColorFilter(geColorMatrix()));

                            }
                        });

                    }
                    return false;
                }
            }).into(image);
}

From source file:tv.piratemedia.flightcontroller.BluetoothComputerFragment.java

public void updateLEDStatus(boolean on, int color) {
    sendCommand((byte) 5, (byte) (on ? 0 : 1), 1);
    if (on) {//  www  .j  a  va  2  s  .c  o m
        LedColor.setBackgroundColor(color);
        float[] hsv = new float[3];
        Color.colorToHSV(color, hsv);
        int hue = Math.round(hsv[0] * 0.708f);
        sendCommand((byte) 5, (byte) 2, hue);
    } else {
        LedColor.setBackgroundColor(Color.BLACK);
    }
}

From source file:info.tellmetime.TellmetimeActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_tellmetime);

    mDensity = getResources().getDisplayMetrics().density;
    mScreenWidth = getResources().getDisplayMetrics().widthPixels;
    mScreenHeight = getResources().getDisplayMetrics().heightPixels;
    mShorterEdge = Math.min(mScreenWidth, mScreenHeight);
    mTouchSlop = ViewConfiguration.get(this).getScaledTouchSlop();
    mBacklightLight = getResources().getColor(R.color.backlight_light);
    mBacklightDark = getResources().getColor(R.color.backlight_dark);

    // Restore background and highlight colors from saved values or set defaults.
    mSettings = getSharedPreferences("PREFS", Context.MODE_PRIVATE);
    mHighlightColor = mSettings.getInt(HIGHLIGHT, Color.WHITE);
    mBacklightColor = mSettings.getInt(BACKLIGHT, mBacklightLight);
    mBackgroundColor = mSettings.getInt(BACKGROUND, getResources().getColor(R.color.background));
    mBackgroundMode = mSettings.getInt(BACKGROUND_MODE, MODE_BACKGROUND_SOLID);
    mHighlightPosition = mSettings.getFloat(POSITION, 0.0f);
    mMinutesSize = mSettings.getInt(MINUTES_SIZE, 36);
    isNightMode = mSettings.getBoolean(NIGHTMODE, false);

    // Dim the navigation bar.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
        getWindow().getDecorView().setSystemUiVisibility(isNightMode ? View.SYSTEM_UI_FLAG_LOW_PROFILE : 0);

    mSurface = (RelativeLayout) findViewById(R.id.surface);
    mSurface.setBackgroundColor(mBackgroundColor);

    resizeClock();//from   w w w  .ja  v  a2  s  .  co m

    Typeface mTypefaceBold = Typeface.createFromAsset(getAssets(), "Roboto-BoldCondensed.ttf");

    // Set typeface of all items in the clock to Roboto and dim each one and drop shadow on them.
    final LinearLayout mClock = (LinearLayout) findViewById(R.id.clock);
    for (int i = 0; i < mClock.getChildCount(); i++) {
        LinearLayout row = (LinearLayout) mClock.getChildAt(i);

        for (int j = 0; j < row.getChildCount(); j++) {
            TextView tv = (TextView) row.getChildAt(j);

            tv.setTypeface(mTypefaceBold);
            tv.setTextColor(mBacklightColor);
            tv.setShadowLayer(mShorterEdge / 200 * mDensity, 0, 0, mBacklightColor);
        }
    }

    ViewGroup minutesDots = (ViewGroup) findViewById(R.id.minutes_dots);
    for (int i = 0; i < minutesDots.getChildCount(); i++) {
        TextView m = (TextView) minutesDots.getChildAt(i);

        m.setTypeface(mTypefaceBold);
        m.setTextColor(mBacklightColor);
        m.setShadowLayer(mShorterEdge / 200 * mDensity, 0, 0, mBacklightColor);
    }

    // Set Roboto font on TextView where it isn't default.
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
        Typeface mTypefaceItalic = Typeface.createFromAsset(getAssets(), "Roboto-CondensedItalic.ttf");

        ((TextView) findViewById(R.id.labelBackground)).setTypeface(mTypefaceBold);
        ((TextView) findViewById(R.id.info_background)).setTypeface(mTypefaceItalic);
        ((TextView) findViewById(R.id.info_image)).setTypeface(mTypefaceItalic);
        ((TextView) findViewById(R.id.labelHighlight)).setTypeface(mTypefaceBold);
        ((TextView) findViewById(R.id.labelBackground)).setTypeface(mTypefaceBold);
        ((TextView) findViewById(R.id.radio_backlight_light)).setTypeface(mTypefaceBold);
        ((TextView) findViewById(R.id.radio_backlight_dark)).setTypeface(mTypefaceBold);
        ((TextView) findViewById(R.id.radio_backlight_highlight)).setTypeface(mTypefaceBold);
        ((TextView) findViewById(R.id.labelMinutes)).setTypeface(mTypefaceBold);
        ((TextView) findViewById(R.id.m1)).setTypeface(mTypefaceBold);
        ((TextView) findViewById(R.id.m2)).setTypeface(mTypefaceBold);
        ((TextView) findViewById(R.id.m3)).setTypeface(mTypefaceBold);
        ((TextView) findViewById(R.id.m4)).setTypeface(mTypefaceBold);
    }

    FrameLayout mTouchZone = (FrameLayout) findViewById(R.id.touchZone);
    mTouchZone.setOnTouchListener(this);
    mTouchZone.setBackgroundColor(
            getResources().getColor(isNightMode ? R.color.night_mode_overlay : android.R.color.transparent));

    mBackgroundImage = (ImageView) findViewById(R.id.background_image);
    switchBackgroundMode(mBackgroundMode);

    RelativeLayout mPanel = (RelativeLayout) findViewById(R.id.panel);
    mPanel.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            mHider.delayedHide(4000);
            return true;
        }
    });

    mHider = new PanelHider(mPanel, this);

    Spinner spinnerBackgroundMode = (Spinner) findViewById(R.id.spinnerBackgroundMode);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.backgrounds_modes,
            android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinnerBackgroundMode.setAdapter(adapter);
    spinnerBackgroundMode.setOnItemSelectedListener(this);
    spinnerBackgroundMode.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            mHider.showNoAutoHide();
            return false;
        }
    });
    spinnerBackgroundMode.setSelection(mBackgroundMode);

    mSeekBarHighlight = (SeekBar) findViewById(R.id.highlightValue);
    mSeekBarHighlight.setOnSeekBarChangeListener(this);

    // Draw rainbow gradient on #mSeekBarHighlight and set position.
    drawRainbow();

    if (mBacklightColor == mBacklightLight)
        ((RadioButton) findViewById(R.id.radio_backlight_light)).setChecked(true);
    else if (mBacklightColor == mBacklightDark)
        ((RadioButton) findViewById(R.id.radio_backlight_dark)).setChecked(true);
    else
        ((RadioButton) findViewById(R.id.radio_backlight_highlight)).setChecked(true);

    SeekBar mSeekBarMinutes = (SeekBar) findViewById(R.id.minutesSize);
    mSeekBarMinutes.setOnSeekBarChangeListener(this);
    mSeekBarMinutes.setProgress(mMinutesSize);

    mHider.hideNow();

    Color.colorToHSV(mBackgroundColor, mHSV);
    mHSV[1] = 1.0f;

    //Trigger initial tick.
    mClockAlgorithm.tickTock();

    // Schedule the clock algorithm to tick every round minute.
    Calendar time = Calendar.getInstance();
    time.set(Calendar.MILLISECOND, 0);
    time.set(Calendar.SECOND, 0);
    time.add(Calendar.MINUTE, 1);

    Timer timer = new Timer();
    timer.schedule(mClockTask, time.getTime(), 60 * 1000);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        mSurface.setAlpha(0.0f);
        mSurface.animate().alpha(1.0f).setDuration(1500);
    }

    // If it is first run, hint to user that panel is available.
    if (!mSettings.contains(HIGHLIGHT))
        showToast(R.string.info_first_run);
}

From source file:com.google.android.apps.muzei.settings.SettingsChooseSourceFragment.java

public void updateSources() {
    mSelectedSource = null;/*from ww w  .  j  a v a  2s  .c  om*/
    Intent queryIntent = new Intent(ACTION_MUZEI_ART_SOURCE);
    PackageManager pm = getActivity().getPackageManager();
    mSources.clear();
    List<ResolveInfo> resolveInfos = pm.queryIntentServices(queryIntent, PackageManager.GET_META_DATA);

    for (ResolveInfo ri : resolveInfos) {
        Source source = new Source();
        source.label = ri.loadLabel(pm).toString();
        source.icon = new BitmapDrawable(getResources(), generateSourceImage(ri.loadIcon(pm)));
        source.componentName = new ComponentName(ri.serviceInfo.packageName, ri.serviceInfo.name);
        if (ri.serviceInfo.descriptionRes != 0) {
            try {
                Context packageContext = getActivity()
                        .createPackageContext(source.componentName.getPackageName(), 0);
                Resources packageRes = packageContext.getResources();
                source.description = packageRes.getString(ri.serviceInfo.descriptionRes);
            } catch (PackageManager.NameNotFoundException e) {
                Log.e(TAG, "Can't read package resources for source " + source.componentName);
            }
        }
        Bundle metaData = ri.serviceInfo.metaData;
        source.color = Color.WHITE;
        if (metaData != null) {
            String settingsActivity = metaData.getString("settingsActivity");
            if (!TextUtils.isEmpty(settingsActivity)) {
                source.settingsActivity = ComponentName
                        .unflattenFromString(ri.serviceInfo.packageName + "/" + settingsActivity);
            }

            String setupActivity = metaData.getString("setupActivity");
            if (!TextUtils.isEmpty(setupActivity)) {
                source.setupActivity = ComponentName
                        .unflattenFromString(ri.serviceInfo.packageName + "/" + setupActivity);
            }

            source.color = metaData.getInt("color", source.color);

            try {
                float[] hsv = new float[3];
                Color.colorToHSV(source.color, hsv);
                boolean adjust = false;
                if (hsv[2] < 0.8f) {
                    hsv[2] = 0.8f;
                    adjust = true;
                }
                if (hsv[1] > 0.4f) {
                    hsv[1] = 0.4f;
                    adjust = true;
                }
                if (adjust) {
                    source.color = Color.HSVToColor(hsv);
                }
                if (Color.alpha(source.color) != 255) {
                    source.color = Color.argb(255, Color.red(source.color), Color.green(source.color),
                            Color.blue(source.color));
                }
            } catch (IllegalArgumentException ignored) {
            }
        }

        mSources.add(source);
    }

    final String appPackage = getActivity().getPackageName();
    Collections.sort(mSources, new Comparator<Source>() {
        @Override
        public int compare(Source s1, Source s2) {
            String pn1 = s1.componentName.getPackageName();
            String pn2 = s2.componentName.getPackageName();
            if (!pn1.equals(pn2)) {
                if (appPackage.equals(pn1)) {
                    return -1;
                } else if (appPackage.equals(pn2)) {
                    return 1;
                }
            }
            return s1.label.compareTo(s2.label);
        }
    });

    redrawSources();
}

From source file:com.skytree.epubtest.BookViewActivity.java

public int getDarkerColor(int color) {
    float[] hsv = new float[3];
    Color.colorToHSV(color, hsv);
    hsv[2] *= 0.8f; // value component
    int darker = Color.HSVToColor(hsv);
    return darker;
}

From source file:com.granita.tasks.ViewTaskFragment.java

public static int darkenColor(int color) {
    float[] hsv = new float[3];
    Color.colorToHSV(color, hsv);
    if (hsv[2] > 0.8) {
        hsv[2] = 0.8f + (hsv[2] - 0.8f) * 0.5f;
        color = Color.HSVToColor(hsv);
    }/*www  .  j  av  a2  s.  c  o m*/
    return color;
}

From source file:com.granita.tasks.ViewTaskFragment.java

public static int darkenColor2(int color) {
    float[] hsv = new float[3];
    Color.colorToHSV(color, hsv);
    hsv[2] = hsv[2] * 0.75f;/*from   w  ww . j  av  a 2  s .co m*/
    color = Color.HSVToColor(hsv);
    return color;
}

From source file:com.atwal.wakeup.battery.util.Utilities.java

/**
 * This picks a dominant color, looking for high-saturation, high-value, repeated hues.
 *
 * @param bitmap  The bitmap to scan// ww w.ja  v  a  2 s  .  com
 * @param samples The approximate max number of samples to use.
 */
public static int findDominantColorByHue(Bitmap bitmap, int samples) {
    final int height = bitmap.getHeight();
    final int width = bitmap.getWidth();
    int sampleStride = (int) Math.sqrt((height * width) / samples);
    if (sampleStride < 1) {
        sampleStride = 1;
    }

    // This is an out-param, for getting the hsv values for an rgb
    float[] hsv = new float[3];

    // First get the best hue, by creating a histogram over 360 hue buckets,
    // where each pixel contributes a score weighted by saturation, value, and alpha.
    float[] hueScoreHistogram = new float[360];
    float highScore = -1;
    int bestHue = -1;

    for (int y = 0; y < height; y += sampleStride) {
        for (int x = 0; x < width; x += sampleStride) {
            int argb = bitmap.getPixel(x, y);
            int alpha = 0xFF & (argb >> 24);
            if (alpha < 0x80) {
                // Drop mostly-transparent pixels.
                continue;
            }
            // Remove the alpha channel.
            int rgb = argb | 0xFF000000;
            Color.colorToHSV(rgb, hsv);
            // Bucket colors by the 360 integer hues.
            int hue = (int) hsv[0];
            if (hue < 0 || hue >= hueScoreHistogram.length) {
                // Defensively avoid array bounds violations.
                continue;
            }
            float score = hsv[1] * hsv[2];
            hueScoreHistogram[hue] += score;
            if (hueScoreHistogram[hue] > highScore) {
                highScore = hueScoreHistogram[hue];
                bestHue = hue;
            }
        }
    }

    SparseArray<Float> rgbScores = new SparseArray<Float>();
    int bestColor = 0xff000000;
    highScore = -1;
    // Go theme_icon_back over the RGB colors that match the winning hue,
    // creating a histogram of weighted s*v scores, for up to 100*100 [s,v] buckets.
    // The highest-scoring RGB color wins.
    for (int y = 0; y < height; y += sampleStride) {
        for (int x = 0; x < width; x += sampleStride) {
            int rgb = bitmap.getPixel(x, y) | 0xff000000;
            Color.colorToHSV(rgb, hsv);
            int hue = (int) hsv[0];
            if (hue == bestHue) {
                float s = hsv[1];
                float v = hsv[2];
                int bucket = (int) (s * 100) + (int) (v * 10000);
                // Score by cumulative saturation * value.
                float score = s * v;
                Float oldTotal = rgbScores.get(bucket);
                float newTotal = oldTotal == null ? score : oldTotal + score;
                rgbScores.put(bucket, newTotal);
                if (newTotal > highScore) {
                    highScore = newTotal;
                    // All the colors in the winning bucket are very similar. Last in wins.
                    bestColor = rgb;
                }
            }
        }
    }
    return bestColor;
}

From source file:com.google.android.apps.muzei.settings.ChooseSourceFragment.java

public void updateSources() {
    mSelectedSource = null;//ww w  . jav  a 2  s.c o m
    Intent queryIntent = new Intent(ACTION_MUZEI_ART_SOURCE);
    PackageManager pm = getContext().getPackageManager();
    mSources.clear();
    List<ResolveInfo> resolveInfos = pm.queryIntentServices(queryIntent, PackageManager.GET_META_DATA);

    for (ResolveInfo ri : resolveInfos) {
        Source source = new Source();
        source.label = ri.loadLabel(pm).toString();
        source.icon = new BitmapDrawable(getResources(), generateSourceImage(ri.loadIcon(pm)));
        source.targetSdkVersion = ri.serviceInfo.applicationInfo.targetSdkVersion;
        source.componentName = new ComponentName(ri.serviceInfo.packageName, ri.serviceInfo.name);
        if (ri.serviceInfo.descriptionRes != 0) {
            try {
                Context packageContext = getContext()
                        .createPackageContext(source.componentName.getPackageName(), 0);
                Resources packageRes = packageContext.getResources();
                source.description = packageRes.getString(ri.serviceInfo.descriptionRes);
            } catch (PackageManager.NameNotFoundException | Resources.NotFoundException e) {
                Log.e(TAG, "Can't read package resources for source " + source.componentName);
            }
        }
        Bundle metaData = ri.serviceInfo.metaData;
        source.color = Color.WHITE;
        if (metaData != null) {
            String settingsActivity = metaData.getString("settingsActivity");
            if (!TextUtils.isEmpty(settingsActivity)) {
                source.settingsActivity = ComponentName
                        .unflattenFromString(ri.serviceInfo.packageName + "/" + settingsActivity);
            }

            String setupActivity = metaData.getString("setupActivity");
            if (!TextUtils.isEmpty(setupActivity)) {
                source.setupActivity = ComponentName
                        .unflattenFromString(ri.serviceInfo.packageName + "/" + setupActivity);
            }

            source.color = metaData.getInt("color", source.color);

            try {
                float[] hsv = new float[3];
                Color.colorToHSV(source.color, hsv);
                boolean adjust = false;
                if (hsv[2] < 0.8f) {
                    hsv[2] = 0.8f;
                    adjust = true;
                }
                if (hsv[1] > 0.4f) {
                    hsv[1] = 0.4f;
                    adjust = true;
                }
                if (adjust) {
                    source.color = Color.HSVToColor(hsv);
                }
                if (Color.alpha(source.color) != 255) {
                    source.color = Color.argb(255, Color.red(source.color), Color.green(source.color),
                            Color.blue(source.color));
                }
            } catch (IllegalArgumentException ignored) {
            }
        }

        mSources.add(source);
    }

    final String appPackage = getContext().getPackageName();
    Collections.sort(mSources, new Comparator<Source>() {
        @Override
        public int compare(Source s1, Source s2) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                boolean target1IsO = s1.targetSdkVersion >= Build.VERSION_CODES.O;
                boolean target2IsO = s2.targetSdkVersion >= Build.VERSION_CODES.O;
                if (target1IsO && !target2IsO) {
                    return 1;
                } else if (!target1IsO && target2IsO) {
                    return -1;
                }
            }
            String pn1 = s1.componentName.getPackageName();
            String pn2 = s2.componentName.getPackageName();
            if (!pn1.equals(pn2)) {
                if (appPackage.equals(pn1)) {
                    return -1;
                } else if (appPackage.equals(pn2)) {
                    return 1;
                }
            }
            return s1.label.compareTo(s2.label);
        }
    });

    redrawSources();
}

From source file:com.granita.tasks.ViewTaskFragment.java

@SuppressLint("NewApi")
private void updateColor(float percentage) {
    if (getActivity() instanceof TaskListActivity) {
        return;//from  w  w w.  ja  v a  2s . co m
    }

    float[] hsv = new float[3];
    Color.colorToHSV(mListColor, hsv);

    if (VERSION.SDK_INT >= 11 && mColorBar != null) {
        percentage = Math.max(0, Math.min(Float.isNaN(percentage) ? 0 : percentage, 1));
        percentage = (float) Math.pow(percentage, 1.5);

        int newColor = darkenColor2(mListColor);

        hsv[2] *= (0.5 + 0.25 * percentage);

        ActionBar actionBar = ((ActionBarActivity) getActivity()).getSupportActionBar();
        actionBar.setBackgroundDrawable(
                new ColorDrawable((newColor & 0x00ffffff) | ((int) (percentage * 255) << 24)));

        // this is a workaround to ensure the new color is applied on all devices, some devices show a transparent ActionBar if we don't do that.
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setDisplayShowTitleEnabled(false);

        mColorBar.setBackgroundColor(mListColor);

        if (VERSION.SDK_INT >= 21) {
            Window window = getActivity().getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(newColor | 0xff000000);
        }
    }

    if (mActionButton != null) {
        // adjust color of action button
        if (hsv[0] > 70 && hsv[0] < 170 && hsv[2] < 0.62) {
            mActionButton.setBackgroundResource(R.drawable.bg_actionbutton_light);
        } else {
            mActionButton.setBackgroundResource(R.drawable.bg_actionbutton);
        }
    }
}