我是一个 android/java 新手,正在开发一个简单的应用程序,该应用程序将从色轮中挑选的颜色生成和谐的颜色。问题是我什至无法在色轮下方的框中显示正确的颜色(触摸色轮上的黄色会生成紫色:S)我不明白发生了什么。我也用几个不同的图像尝试了这段代码,生成的颜色仍然全部关闭..
public class MainActivity extends Activity {
ImageView cw;
Bitmap cwBmp;
ColourView colourArray;
int redValue;
int blueValue;
int greenValue;
int argb;
int alpha;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
colourArray = new ColourView(this);
RelativeLayout rl = (RelativeLayout) findViewById(R.id.layout);
rl.addView(colourArray);
cw = (ImageView) findViewById(R.id.colourwheelpic);
BitmapDrawable drawable = (BitmapDrawable) cw.getDrawable();
cwBmp = drawable.getBitmap();
cw.setOnTouchListener(new ImageView.OnTouchListener(){
@Override
public boolean onTouch(View arg0, MotionEvent event) {
int touchX = (int)event.getX();
int touchY = (int)event.getY();
int pixel;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touchX = (int)event.getX();
touchY = (int)event.getY();
case MotionEvent.ACTION_UP:
pixel = cwBmp.getPixel(touchX,touchY);
redValue = Color.red(pixel);
alpha = Color.alpha(pixel);
blueValue = Color.blue(pixel);
greenValue = Color.green(pixel);
argb = Color.argb(alpha, redValue,blueValue,greenValue);
colourArray.colors.clear();
colourArray.colors.add(argb);
colourArray.invalidate();
return true;
}
return false;
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
colourArray 是一个 ColorView 对象
public class ColourView extends View {
Paint paint = new Paint();
ArrayList<Integer> colors = new ArrayList<Integer>();
public ColourView(Context context) {
super(context);
colors.add(Color.WHITE);
}
public void onDraw(Canvas canvas){
int i = 0;
while ( i < 220 ){
paint.setColor(colors.get(0));
paint.setStrokeWidth(0);
canvas.drawRect(25+ (44*i), 500,69+(44*i),550, paint);
i = i + 1;
}
}
private int getRandomInt(){
int upper = colors.size();
int r = (int) (Math.random() * (upper));
return r;
}
}
这是我的布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ImageView
android:id="@+id/colourwheelpic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="@drawable/colourwheelbmp" />
</RelativeLayout>