- 浏览: 14600 次
文章分类
最新评论
Bitmap和canvas的应用
画虚线
SET_WALLPAPER
public class Canvas extends Activity implements OnTouchListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);// 去掉信息栏
setContentView(R.layout.main);
iv = new ImageView(this);
bitmap = Bitmap.createBitmap(800, 480, Bitmap.Config.ARGB_8888);
iv.setImageBitmap(bitmap);
LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
ll.addView(iv, new LayoutParams(800, 480));
ll.setOnTouchListener(this);
}
private android.graphics.Canvas myCanvas;
private Bitmap bitmap;
private Paint myPaint;
private ImageView iv;
private float left;
private float top;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
myCanvas = new android.graphics.Canvas(bitmap);
myPaint = new Paint();
// myPaint.setAntiAlias(true);//抗锯齿
//
// RectF oval = new RectF(0, 0, 200, 200);
// myPaint.setColor(Color.DKGRAY);
// myCanvas.drawArc(oval, 0, 360, true, myPaint);
//
// myPaint.setColor(Color.LTGRAY);
//
// myCanvas.drawArc(oval, 0, 320, true, myPaint);
// RectF eyes = new RectF(100, 20, 130, 50);
// myPaint.setColor(Color.RED);
// myCanvas.drawArc(eyes, 0, 360, true, myPaint);
// myCanvas.drawCircle(200, 300, 100, myPaint);
System.out.println("======================");
iv.setImageBitmap(bitmap);
left = event.getX();
top = event.getY();
break;
case MotionEvent.ACTION_MOVE:
// myCanvas.drawPoint(event.getX(), event.getY(), myPaint);
// myPaint.setTypeface(Typeface.createFromFile("/sdcard/stxingka.ttf"));
// myPaint.setTextSize(50);
// myCanvas.drawText("Hello World!", event.getX(), event.getY(), myPaint);
PathEffect pathEffect = new DashPathEffect(
new float[] { 5, 5, 5, 5 }, 1);
myPaint.setColor(Color.GREEN);
myPaint.setPathEffect(pathEffect);
myPaint.setStyle(Style.STROKE);
myPaint.setStrokeWidth(3);
myCanvas.drawARGB(255, 20, 30, 41);
myCanvas.drawRect(new RectF(left, top, event.getX(), event.getY()),myPaint);
iv.setImageBitmap(bitmap);
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
一个让Gridview项移动的例子:
public class Utils {
public static int[] image = { R.drawable.mb5u1_mb5ucom, R.drawable.mb5u2_mb5ucom,
R.drawable.mb5u3_mb5ucom, R.drawable.mb5u4_mb5ucom,
R.drawable.mb5u5_mb5ucom, R.drawable.mb5u6_mb5ucom,
R.drawable.mb5u7_mb5ucom, R.drawable.mb5u8_mb5ucom,
R.drawable.mb5u9_mb5ucom, R.drawable.mb5u10_mb5ucom,
R.drawable.mb5u11_mb5ucom, R.drawable.mb5u12_mb5ucom,
R.drawable.mb5u13_mb5ucom, R.drawable.mb5u14_mb5ucom,
R.drawable.mb5u15_mb5ucom, R.drawable.mb5u16_mb5ucom,
R.drawable.mb5u17_mb5ucom, R.drawable.mb5u18_mb5ucom,
R.drawable.mb5u19_mb5ucom, R.drawable.mb5u20_mb5ucom,
R.drawable.mb5u21_mb5ucom, R.drawable.mb5u22_mb5ucom,
R.drawable.mb5u23_mb5ucom, R.drawable.mb5u24_mb5ucom,
R.drawable.mb5u25_mb5ucom, R.drawable.mb5u26_mb5ucom,
R.drawable.mb5u27_mb5ucom, R.drawable.mb5u28_mb5ucom,
R.drawable.mb5u29_mb5ucom, R.drawable.mb5u30_mb5ucom,
R.drawable.mb5u31_mb5ucom, R.drawable.mb5u32_mb5ucom,
R.drawable.mb5u33_mb5ucom, R.drawable.mb5u34_mb5ucom,
R.drawable.mb5u35_mb5ucom, R.drawable.mb5u36_mb5ucom,
R.drawable.mb5u37_mb5ucom, R.drawable.mb5u38_mb5ucom,
R.drawable.mb5u39_mb5ucom, R.drawable.mb5u40_mb5ucom,
R.drawable.mb5u41_mb5ucom, R.drawable.mb5u42_mb5ucom,
R.drawable.mb5u43_mb5ucom, R.drawable.mb5u44_mb5ucom };
public static ArrayList<Map<String, Object>> getData() {
ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
for (int i = 0; i < 23; i++) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("img", image[i]);
list.add(map);
}
return list;
}
正式绑定
public class MyGridViewDemo extends Activity implements OnTouchListener {
private RelativeLayout myRl;
private GridView myGridView;
private ArrayList<Map<String, Object>> mArray;
private MyAdapter adapter;
private int mDragViewX;
private int mDragViewY;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);// 去掉信息栏
setContentView(R.layout.main);
myRl = (RelativeLayout) findViewById(R.id.ll);
myGridView = new GridView(this);
mArray = Utils.getData();
System.out.println(mArray.size());
adapter = new MyAdapter(this, myGridView.getId(), mArray);
myGridView.setAdapter(adapter);
// GridView的列数
myGridView.setNumColumns(5);
myRl.addView(myGridView);
myGridView.setOnTouchListener(this);
}
class MyAdapter extends ArrayAdapter<Map<String, Object>> {
public MyAdapter(Context context, int textViewResourceId,
List<Map<String, Object>> objects) {
super(context, textViewResourceId, objects);
}
public ArrayList<Map<String, Object>> getList() {
return mArray;
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = getLayoutInflater();
row = (View) inflater.inflate(R.layout.mygrid_item, null);
}
ImageView imageView = (ImageView) row.findViewById(R.id.img);
imageView.setImageResource(Integer.valueOf(mArray.get(position)
.get("img").toString()));
if (from == position) {
imageView.setVisibility(View.INVISIBLE);
} else if (View.INVISIBLE == imageView.getVisibility()) {
imageView.setVisibility(View.VISIBLE);
}
Log.i("ivan", "position =" + position + "aniFrom =" + aniFrom
+ "aniTo" + aniTo);
Animation ani = null;
if (position > aniTo && position <= aniFrom) {
if (position % 5 == 0) {
ani = new TranslateAnimation(355, 0, -85, 0);
} else {
ani = new TranslateAnimation(-60, 0, 0, 0);
}
} else if (position < aniTo && position >= aniFrom) {
if (position % 5 == 4) {
ani = new TranslateAnimation(-355, 0, 85, 0);
} else {
ani = new TranslateAnimation(60, 0, 0, 0);
}
}
if (ani != null) {
ani.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
onAnimation = true;
}
@Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationEnd(Animation animation) {
// TODO Auto-generated method stub
onAnimation = false;
}
});
ani.setDuration(500);
imageView.setAnimation(ani);
}
return imageView;
}
}
private boolean onAnimation = false;
private int from = -1;
private int to = -1;
private int aniTo;
private int aniFrom;
@Override
public boolean onTouch(View v, MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
int position = myGridView.pointToPosition(x, y);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// 如果没有点击到图片直接break
System.out.println("position =" + position);
if (position == -1) {
break;
}
// 获取到点击的View
View tempView = myGridView.getChildAt(position
- myGridView.getFirstVisiblePosition());
System.out.println("tempView =" + tempView);
if (tempView == null) {
break;
}
// 开启View的缓存
tempView.setDrawingCacheEnabled(true);
// tempView.getTop()获取到tempView自身的位置,因为按下的时候应该显示的位置和他自身的位置相同
// tempView.getLeft() 同理
startDragging(tempView.getDrawingCache(), tempView.getTop(),
tempView.getLeft());
// 获取点击的位置距所点击图片顶部的距离mDragViewX,mDragViewY
mDragViewX = x - tempView.getLeft();
mDragViewY = y - tempView.getTop();
from = position;
tempView.setVisibility(View.INVISIBLE);
break;
case MotionEvent.ACTION_MOVE:
if (myDragView != null) {
RelativeLayout.LayoutParams rllp = (LayoutParams) myDragView
.getLayoutParams();
rllp.leftMargin = x - mDragViewX;
rllp.topMargin = y - mDragViewY;
myDragView.setLayoutParams(rllp);
}
if (position != -1) {
to = position;
}
Log.i("ivan", "form=" + from);
if (from != to && from != -1 && to != -1 &&!onAnimation) {
aniFrom = from;
aniTo = to;
Map<String, Object> temp = adapter.getItem(from);
adapter.remove(temp);
adapter.insert(temp, to);
from = to;
}
break;
case MotionEvent.ACTION_UP:
if (myDragView != null) {
// 把myDragView 从RelativeLayout中删除
myRl.removeView(myDragView);
}
// 获取到松手位置的图片让其显示
View end = myGridView.getChildAt(from
- myGridView.getFirstVisiblePosition());
if (end != null) {
end.setVisibility(View.VISIBLE);
}
from = -1;
to = -1;
break;
}
return true;
}
private ImageView myDragView;
private void startDragging(Bitmap tempBitmap, int top, int left) {
ImageView iv = new ImageView(getApplication());
RelativeLayout.LayoutParams rllp = new RelativeLayout.LayoutParams(-2,
-2);
rllp.leftMargin = left;
rllp.topMargin = top;
iv.setImageBitmap(tempBitmap);
// 测试方法看iv是否有值 作用是让此View填充全屏
// setContentView(iv);
myDragView = iv;
myRl.addView(myDragView, rllp);
// 两种写法一样
// mDragView.setLayoutParams(rllp);
// rl.addView(mDragView);
}
---------------------------------------------
dragwindow 图片拖动
public class DragwindowActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
//设置窗体的属性
WindowManager.LayoutParams params = new LayoutParams();
params.height = WindowManager.LayoutParams.FILL_PARENT;
params.width = WindowManager.LayoutParams.FILL_PARENT;
params.format = PixelFormat.TRANSLUCENT;
DisplayMetrics dm = getResources().getDisplayMetrics();
final int screenWidth = dm.widthPixels;
final int screenHeight = dm.heightPixels-50; //拖动窗体内的范围
//把要拖动view布局文件孵化成view
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.main, null);
ImageButton button = (ImageButton) view.findViewById(R.id.ib_tt);
button.setOnTouchListener(new OnTouchListener() {
int lastX,lastY; //焦点
@Override
public boolean onTouch(View v, MotionEvent event) {
int me = event.getAction();
Log.i("TAG", "Touch:"+me); //按下是0,拖动是2,弹起是1;
switch(me){
case MotionEvent.ACTION_DOWN:
lastX = (int) event.getRawX();
lastY = (int) event.getRawY();
Log.i("TAG", "down x="+lastX+" ,y="+lastY);
break;
case MotionEvent.ACTION_MOVE:
int dx = (int) event.getRawX()-lastX;
int dy = (int) event.getRawY()-lastY;
Log.i("TAG", "d x="+dx+" ,d y="+dy); //拖动的坐标
//拖动移位后的坐标
int left = v.getLeft() + dx;
int top = v.getTop() + dy;
int right = v.getRight() + dx;
int bottom = v.getBottom() + dy;
if(left<0){
left = 0;
right=left+v.getWidth();
}
if(right>screenWidth){
right=screenWidth;
left = right-v.getWidth();
}
if(top<0){
top=0;
bottom = top+v.getHeight();
}
if(bottom>screenHeight){
bottom = screenHeight;
top = bottom - v.getHeight();
}
v.layout(left, top, right, bottom);
lastX = (int) event.getRawX();
lastY = (int) event.getRawY();
break;
case MotionEvent.ACTION_UP:
break;
}
return false;
}
});
WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
manager.addView(view, params);
}
----------------------读取相册--画图保存
ImageView iv1;
Canvas canvas ;
Bitmap alteredBitmap;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
iv1 =(ImageView) findViewById(R.id.iv1);
iv1.setOnTouchListener(this);
}
public void selectImage(View view) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 200);
}
public void saveImage(View view){
try {
Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, new ContentValues());
OutputStream os = getContentResolver().openOutputStream(uri);
Boolean result = alteredBitmap.compress(CompressFormat.JPEG, 50, os);
if(result){
Toast.makeText(this, "保存成功", 1).show();
Intent intent = new Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://"+Environment.getExternalStorageDirectory()));
sendBroadcast(intent);
}else{
Toast.makeText(this, "保存失败", 1).show();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 200) {
Uri uri = data.getData();
try {
// InputStream is =getContentResolver().openInputStream(uri);
//得到屏幕大小
Display currentDisplay = getWindowManager().getDefaultDisplay();
int dw = currentDisplay.getWidth();
int dh = currentDisplay.getHeight();
System.out.println(dw+"--"+dh);
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
// 如果设置了injustDecodeBounds这个属性,不会真的解析bitmap,只返回bitmap的宽高和图片属性
bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile("/sdcard/066.JPG",
bmpFactoryOptions); //参数传入只为得到bmp图属性 ,再缩小
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;
}
}
// 把inJustDecodeBounds设置为false,这样才会真正的decode这个位图
bmpFactoryOptions.inJustDecodeBounds = false;
//得到新图片流
InputStream newis = getContentResolver().openInputStream(uri);
bmp = BitmapFactory.decodeStream(newis, null, bmpFactoryOptions);
// 创建一个bitmap的拷贝
// 创建了一个空的bitmap ,用原来的参数填充
alteredBitmap = Bitmap.createBitmap(bmp.getWidth(),
bmp.getHeight(), bmp.getConfig());
// 创建一个画布
canvas = new Canvas(alteredBitmap);
// 创建一个画笔
Paint paint = new Paint();
Matrix matrix = new Matrix();
canvas.drawBitmap(bmp, matrix, paint);
iv1.setImageBitmap(alteredBitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
float downx = 0;
float downy = 0;
float upx = 0;
float upy = 0;
@Override
public boolean onTouch(View v, MotionEvent event) {
int eventtype = event.getAction();
Paint paint = new Paint();
paint.setColor(Color.GREEN);
paint.setStrokeWidth(5);
switch (eventtype) {
case MotionEvent.ACTION_DOWN:
downx = event.getX();
downy = event.getY();
break;
case MotionEvent.ACTION_MOVE:
upx = event.getX();
upy = event.getY();
canvas.drawLine(downx, downy, upx, upy, paint);
iv1.invalidate();
downx = upx;
downy = upy;
break;
case MotionEvent.ACTION_UP:
upx = event.getX();
upy = event.getY();
canvas.drawLine(downx, downy, upx, upy, paint);
iv1.invalidate();
break;
}
return true;
}
转载于:https://my.oschina.net/u/175434/blog/699976
相关推荐
在Android UI开发中,Bitmap和Canvas是两个非常重要的概念,它们是实现图形和图像处理的基础。Bitmap类代表了位图图像,而Canvas则用于在屏幕上画图,包括图像、文字和其他图形元素。在这个实例中,我们将深入理解...
在Android UI开发中,Bitmap和Canvas是两个非常重要的概念,它们是实现自定义视图、图形绘制和图像处理的关键工具。Bitmap是Android中用于表示位图图像的数据结构,而Canvas则是一个画布,用于在屏幕上绘制这些位图...
在Android平台上,绘制图形是一项基本任务,涉及到多个关键类,如Bitmap、Drawable和Canvas,以及Paint。这些类共同构成了Android图形系统的核心,使得开发者能够创建丰富的用户界面和自定义视图。 首先,Bitmap是...
Canvas canvas = new Canvas(canvasBitmap); // 绘制裁剪后的Bitmap canvas.drawBitmap(croppedBitmap, 0, 0, null); // 添加其他图形或文字绘制... // 保存到文件或进行其他操作... ``` 在实际应用中,我们可能...
总的来说,Activity间的Bitmap传递需要考虑内存管理和效率,合理选择传递方式,并结合优化策略,确保应用的稳定性和性能。通过理解这些知识点,开发者能更好地处理Android应用中的图像数据传输。
在实际开发中,理解并掌握Bitmap的这些知识点,能帮助开发者更高效地处理图像,避免内存泄露和性能瓶颈,提升应用的用户体验。通过深入学习和实践,你将能够灵活运用Bitmap,实现丰富的图形效果。
在Android图形系统中,`Canvas`是用于在Bitmap或Surface上进行绘图操作的重要类。它提供了各种绘制路径、文本、矩形、圆形以及其他图形的方法。`save()`和`restore()`是`Canvas`中两个非常关键的方法,它们主要用于...
此外,还可以使用内存缓存(如LruCache)和磁盘缓存(如DiskLruCache)来避免重复加载同一图片,提高应用性能。 3. 展示Bitmap: 将Bitmap显示到ImageView上,可以通过设置ImageView的`setImageBitmap()`方法。...
在Android开发中,Canvas是图形绘制的核心工具,它允许开发者在Bitmap上进行各种形状和图像的绘制。本文将深入探讨如何使用Canvas来绘制正方形、长方形和圆形,以及涉及的相关知识点。 首先,Canvas是Android的图形...
在Android开发中,`Paint`和`Canvas`是两个至关重要的图形绘制类,它们共同构成了Android图形绘制的基础。本文将详细解析这两个类的应用,并通过一个名为"Canvas&PaintDemo"的示例项目来深入理解其工作原理。 首先...
5. 最后,使用Canvas的drawBitmap方法,传入旋转后的Bitmap和旋转中心点,将其绘制到圆形Bitmap上。 这个过程中,关键在于正确地设置BitmapShader和PorterDuff.Mode,以及合理地使用Matrix进行旋转操作。如果要处理...
在Delphi编程环境中,Canvas对象是...通过熟练掌握Canvas的使用,开发者可以创造出丰富多样的视觉效果和应用程序功能。这个“Delphi Canvas方法在图片上写入文字.rar”压缩包,无疑是学习和提升这方面的技能的好资源。
通过分析这个压缩包中的"4-7-2(Canvas画布)"文件,开发者可以学习如何创建Canvas,使用Paint设置样式,以及如何绘制基本图形和Bitmap。实践中,不断试验和调整,掌握Canvas的使用将极大地提升你在Android应用开发中...
Canvas是Android系统中用于图形绘制的核心类,它在Android的视图系统中扮演着至关重要的角色。通过Canvas,开发者可以实现在屏幕...通过不断实践和学习,我们可以熟练地运用Canvas,创造出令人惊叹的Android应用界面。
4. 在Canvas上绘制原始Bitmap,这样旋转的效果就会被应用到新的Bitmap上。 ```java canvas.drawBitmap(bitmap, 0, 0, null); ``` 5. 最后,释放原始Bitmap资源,因为新的rotatedBitmap已经包含了旋转后的图像。 `...
以上就是关于Android中Drawable和Bitmap相互转换的方法、注意事项以及应用场景的详细解释。理解并熟练运用这些知识,能够帮助开发者更有效地处理图像资源,提高应用的性能和用户体验。在实际项目中,要根据具体需求...
在这个“bitmap理解学习例子”中,我们将深入探讨Bitmap的使用和优化,以提高应用程序的性能。 1. **Bitmap的基本操作**: - **创建Bitmap**:可以从资源文件、文件路径或InputStream创建Bitmap。例如,`...
在实际应用中,`Paint`和`Canvas`常常结合使用,先通过`Paint`设置好绘制样式,然后在`Canvas`上进行绘制操作。例如,你可以创建一个`Bitmap`,然后在它的`Canvas`上画一个红色的圆: ```java Bitmap bitmap = ...
5. 应用颜色和渐变,增加视觉效果。 6. 考虑性能优化,避免过度绘制。 通过以上的步骤和技巧,我们可以创造出独特的Android机器人形象,展示出Canvas类的强大功能。在实践中不断探索和学习,你将能够熟练地运用...
- 除了Bitmap,Canvas还可以用于SurfaceView和View的onDraw()方法中,用于绘制UI组件。 2. **创建Canvas** - 可以通过Bitmap的`createBitmap()`或`copy()`方法创建一个新的Canvas实例,然后在该实例上进行绘制。 ...