我正在制作一个应用程序,该应用程序中我使用“相机/画廊意图”选择图像,然后将其设置为ImageView。在图像上的onTouch之后(在ImageView中),我得到了图像的触摸像素的颜色的十六进制,RGB和HSL值。
这对于第一次导入的图像效果很好,但是当我第二次导入图像并触摸该新图像时,它为我提供了先前图像的颜色。
这是我的代码:
package com.blogspot.atifsoftwares.colorslab;
import android.Manifest;
import android.content.ClipboardManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.text.NumberFormat;
public class PickFromImageActivity extends AppCompatActivity {
ImageView mImageView;
TextView mResultTv;
ImageButton mCopyBtn, mShareBtn;
Bitmap bitmap;
View view;
Uri image_uri;
private static final int IMAGE_PICK_GALLERY_CODE = 1000;
private static final int IMAGE_PICK_CAMERA_CODE = 1001;
private static final int PERMISSION_READ_STORAGE_CODE = 1002;
private static final int PERMISSION_WRITE_STORAGE_CODE = 1003;
private static final int PERMISSION_CAMERA_CODE = 1004;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pick_from_image);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle("Color Picker");
actionBar.setSubtitle("Pick color from Image");
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
mImageView =findViewById(R.id.imageIv);
mResultTv = findViewById(R.id.restultTv);
mCopyBtn = findViewById(R.id.copyBtn);
mShareBtn = findViewById(R.id.shareBtn);
view = findViewById(R.id.colorView);
mImageView.setDrawingCacheEnabled(true);
mImageView.buildDrawingCache(true);
mImageView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE){
bitmap = mImageView.getDrawingCache();
int pixel = bitmap.getPixel((int)event.getX(), (int) event.getY());
int r = Color.red(pixel);
int g = Color.green(pixel);
int b = Color.blue(pixel);
int color = Color.TRANSPARENT;
Drawable background = view.getBackground();
if (background instanceof ColorDrawable)
color = ((ColorDrawable) background).getColor();
view.setBackgroundColor(Color.rgb(r,g,b));
mResultTv.setText("HEX: "+ String.format("#%06X", 0xFFFFFF & color)
+"\nRGB: "+ r +", "+ g +", "+ b
+"\nHSL: "+ rgbToHsl(r,g,b));
}
return true;
}
});
mCopyBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String data = mResultTv.getText().toString();
ClipboardManager cb = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
cb.setText(data);
Toast.makeText(PickFromImageActivity.this, "Copied...!", Toast.LENGTH_SHORT).show();
}
});
mShareBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String data = mResultTv.getText().toString();
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, data);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
});
}
private String rgbToHsl(int r, int g, int b) {
final float rf = r / 255f;
final float gf = g / 255f;
final float bf = b / 255f;
final float max = Math.max(rf, Math.max(gf, bf));
final float min = Math.min(rf, Math.min(gf, bf));
final float deltaMaxMin = max - min;
float h, s;
float l = (max + min) / 2f;
if (max == min) {
// Monochromatic
h = s = 0f;
} else {
if (max == rf) {
h = ((gf - bf) / deltaMaxMin) % 6f;
} else if (max == gf) {
h = ((bf - rf) / deltaMaxMin) + 2f;
} else {
h = ((rf - gf) / deltaMaxMin) + 4f;
}
s = deltaMaxMin / (1f - Math.abs(2f * l - 1f));
}
h = (h * 60f) % 360f;
s = s*100;
l = l*100;
NumberFormat formH = NumberFormat.getNumberInstance();
formH.setMinimumFractionDigits(0);
formH.setMaximumFractionDigits(0);
String formattedH = formH.format(h);
NumberFormat formS = NumberFormat.getNumberInstance();
formS.setMinimumFractionDigits(0);
formS.setMaximumFractionDigits(0);
String formattedS = formS.format(s);
NumberFormat formL = NumberFormat.getNumberInstance();
formL.setMinimumFractionDigits(0);
formL.setMaximumFractionDigits(0);
String formattedL = formL.format(l);
return ""+ formattedH +", "+ formattedS +"%, "+ formattedL +"%";
}
public void pickCamera(){
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From Camera");
image_uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_CODE);
}
public void pickGallery(){
//intent to pick image
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, IMAGE_PICK_GALLERY_CODE);
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
menu.findItem(R.id.action_search).setVisible(false);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_about) {
startActivity(new Intent(this, AboutActivity.class));
return true;
} else if (id == R.id.action_rate) {
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.blogspot.atifsoftwares.colorslab")));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.blogspot.atifsoftwares.colorslab")));
}
return true;
} else if (id == R.id.action_more) {
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/dev?id=6868537621115215530")));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/dev?id=6868537621115215530")));
}
return true;
}
else if (id == R.id.action_share) {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "\"Colors Lab\" contains important tools such as Popular Colors, Pick Color from color platte, Pick Color from Image, Convert Color from and to Hex, RGB, HSL.:\n https://play.google.com/store/apps/details?id=com.blogspot.atifsoftwares.colorslab";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
else if (id == R.id.action_camera) {
//check runtime permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if (checkSelfPermission(Manifest.permission.CAMERA)
== PackageManager.PERMISSION_DENIED ||
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_DENIED){
//permission not granted, request it.
String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
//show popup for runtime permission
requestPermissions(permissions, PERMISSION_WRITE_STORAGE_CODE);
}
else {
//permission already granted
pickCamera();
}
}
else {
//system os is less then marshmallow
pickCamera();
}
}
else if (id == R.id.action_gallery) {
//check runtime permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_DENIED){
//permission not granted, request it.
String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE};
//show popup for runtime permission
requestPermissions(permissions, PERMISSION_READ_STORAGE_CODE);
}
else {
//permission already granted
pickGallery();
}
}
else {
//system os is less then marshmallow
pickGallery();
}
}
return super.onOptionsItemSelected(item);
}
//handle result of runtime permission
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case PERMISSION_READ_STORAGE_CODE:{
if (grantResults.length >0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED){
//permission was granted
pickGallery();
}
else {
//permission was denied
Toast.makeText(this, "Permission denied...!", Toast.LENGTH_SHORT).show();
}
}
case PERMISSION_CAMERA_CODE:{
if (grantResults.length >0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED){
//permission was granted
pickCamera();
}
else {
//permission was denied
Toast.makeText(this, "Permission denied...!", Toast.LENGTH_SHORT).show();
}
}
}
}
//handle result of picked image
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK){
if (requestCode == IMAGE_PICK_GALLERY_CODE){
//set image to image view
mImageView.setImageURI(data.getData());
}
if (requestCode == IMAGE_PICK_CAMERA_CODE){
//set image to image view
mImageView.setImageURI(image_uri);
}
}
}
}
答案 0 :(得分:1)
添加图像之前 编写这段代码
$('#button1').on('click', function() {
$('body').append($("<div id='chart-" + index + "'></div>"));
Highcharts.chart('chart-' + index, {
series: [{
data: [1, 2, 3]
}]
});
index++;
});
答案 1 :(得分:0)
在添加图像之前添加...
mImageView.setImageBitmap(null);
mImageView.destroyDrawingCache();
答案 2 :(得分:0)
为了获得颜色,首先必须获得用户单击的像素 要获取像素,必须在画布上获取位图,然后读取该单击的像素的RGB值 下面的代码将帮助您做到这一点
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
int pixel = bitmap.getPixel(x,y); // x and y are coordinates
int redValue = Color.red(pixel);
int blueValue = Color.blue(pixel);
int greenValue = Color.green(pixel);
if(pixel == Color.RED){
// color is red
}
您可以使用多个条件或逻辑从以上值创建RGB代码。