0

我有这个类,我想在单击操作栏时将我的绘图保存到 jpeg 文件中。

public class SingleTouchActivity extends Activity {


  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(new SingleTouchEventView(this, null));

    // Create ActionBar
    ActionBar actionBar = getActionBar();
    actionBar.show();

  }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // ActionBar is clicked
        switch (item.getItemId()) {
        case R.id.sig_reset:
            finish();
            Intent sigIntent = new Intent(this, SingleTouchActivity.class);
            startActivity(sigIntent);
            break;
        case R.id.sig_save:
            //Save to image
            break;
        }
        return true;
    }

我在网上搜索,发现了这个代码片段:

view.setDrawingCacheEnabled(true);
Bitmap b = view.getDrawingCache();
b.compress(CompressFormat.JPEG, 95, new FileOutputStream("/some/location/image.jpg"));

和这个:

//createBitmap(int width, int height, Bitmap.Config config)
//    Returns a mutable bitmap with the specified width and height.
Bitmap image = Bitmap.createBitmap(mapRelativeView.getWidth(), mapRelativeView.getHeight(), Bitmap.Config.RGB_565);

//draw(Canvas canvas) -- Manually render this view
//(and all of its children) to the given Canvas.
yourView.draw(new Canvas(image));

//insertImage(ContentResolver cr, Bitmap source, String title, String description)
//    Insert an image and create a thumbnail for it.
//uri is the path after the image has been saved.
String uri = Images.Media.insertImage(getContentResolver(), image, "title", null);

问题是我的 SingleTouchActivity 将 SingleTouchEventView 设置为内容,我不知道如何定义我的视图。

4

1 回答 1

1

这是免费手绘示例,您可以在其中绘制任何内容并将图像保存在 SD 卡中。

在此处下载完整的源表格

这是执行某些特定任务的主要OnCreate()方法。

Like :
  • 检查路径是否存在,如果没有,则设置图像路径。
  • 根据当前日期和时间设置图像名称。
  • 准备屏幕视图。
  • 绘制签名。
  • 存储在 SD 卡中。
  • 使用 Bitmap Image 返回到 Activity,以便可以在 Image View 上设置它。
  • 清除可绘制签名。

       @Override
    public void onCreate(Bundle savedInstanceState)
    {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.signature);
    
    // tempDir = Environment.getExternalStorageDirectory() + "/" +   getResources().getString(R.string.external_dir) + "/";
     ContextWrapper cw = new ContextWrapper(getApplicationContext());
    // File directory = cw.getDir(getResources().getString(R.string.external_dir),  Context.MODE_PRIVATE);
    
    File directory = new File(Environment.getExternalStorageDirectory() + "/Your_Floder_Name");
    

检查路径是否存在,如果没有,则设置图像路径。

if(!directory.exists())

directory.mkdir(); //directory is created;

//prepareDirectory();

根据当前日期和时间设置图像名称。

uniqueId = getTodaysDate() + "_" + getCurrentTime();
current = uniqueId + ".png";
mypath= new File(directory,current);

mContent = (LinearLayout) findViewById(R.id.linearLayout);

绘制签名

mSignature = new signature(this, null);
mSignature.setBackgroundColor(Color.WHITE);

准备屏幕视图。

mContent.addView(mSignature, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);

清除可绘制签名。

mClear = (Button)findViewById(R.id.clear);
mGetSign = (Button)findViewById(R.id.getsign);
mGetSign.setEnabled(false);
mCancel = (Button)findViewById(R.id.cancel);
mView = mContent;

清除可绘制签名。

mClear.setOnClickListener(new OnClickListener()

{
public void onClick(View v)
{
Log.v("log_tag", "Panel Cleared");
mSignature.clear();
mGetSign.setEnabled(false);
}
});

绘制签名

mGetSign.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Log.v("log_tag", "Panel Saved");
// boolean error = captureSignature();
// if(error){
mView.setDrawingCacheEnabled(true);
mSignature.save(mView);
//Bundle b = new Bundle();
// b.putString("status", "done");
Intent intent = new Intent(Capture.this,SigntuareCaptureActivity.class);
// intent.putExtra("imagePath",mypath);
startActivity(intent);
//intent.putExtra("status", "done");
//setResult(RESULT_OK,intent);
finish();
// }
}
});

如果不想绘制签名,请取消。

mCancel.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Log.v("log_tag", "Panel Canceled");
Bundle b = new Bundle();
b.putString("status", "cancel");
Intent intent = new Intent();
intent.putExtras(b);
setResult(RESULT_OK,intent);
finish();
}
});

}

使用当前日期和时间设置图像名称。

private String getTodaysDate()

{

final Calendar c = Calendar.getInstance();
int todaysDate = (c.get(Calendar.YEAR) * 10000) +
((c.get(Calendar.MONTH) + 1) * 100) +
(c.get(Calendar.DAY_OF_MONTH));
Log.w("DATE:",String.valueOf(todaysDate));
return(String.valueOf(todaysDate));

}

private String getCurrentTime()
{

final Calendar c = Calendar.getInstance();
int currentTime = (c.get(Calendar.HOUR_OF_DAY) * 10000) +
(c.get(Calendar.MINUTE) * 100) +
(c.get(Calendar.SECOND));
Log.w("TIME:",String.valueOf(currentTime));
return(String.valueOf(currentTime));

}

如果不存在,请检查您的目录,然后创建新的

private boolean prepareDirectory()
{
try
{
if (makedirs())
{
return true;
}
else
{
return false;
}
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(this, "Could not initiate File System.. Is Sdcard mounted properly?", 1000).show();
return false;
}
}

private boolean makedirs()
{
File tempdir = new File(tempDir);
if (!tempdir.exists())
tempdir.mkdirs();

if (tempdir.isDirectory())
{
File[] files = tempdir.listFiles();
for (File file : files)
{
if (!file.delete())
{
System.out.println("Failed to delete " + file);
}
}
}
return (tempdir.isDirectory());
}

画你的签名

public class signature extends View
{
private static final float STROKE_WIDTH = 5f;
private static final float HALF_STROKE_WIDTH = STROKE_WIDTH / 2;
private Paint paint = new Paint();
private Path path = new Path();

private float lastTouchX;
private float lastTouchY;
private final RectF dirtyRect = new RectF();

public signature(Context context, AttributeSet attrs)
{
super(context, attrs);
paint.setAntiAlias(true);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(STROKE_WIDTH);
}

public void save(View v)
{
Log.v("log_tag", "Width: " + v.getWidth());
Log.v("log_tag", "Height: " + v.getHeight());
if(mBitmap == null)
{
mBitmap = Bitmap.createBitmap (mContent.getWidth(), mContent.getHeight(), Bitmap.Config.RGB_565);
}
Canvas canvas = new Canvas(mBitmap);
try
{

FileOutputStream mFileOutStream = new FileOutputStream(mypath);

v.draw(canvas);
mBitmap.compress(Bitmap.CompressFormat.PNG, 90, mFileOutStream);
mFileOutStream.flush();
mFileOutStream.close();
String url = Images.Media.insertImage(getContentResolver(), mBitmap, "title", null);
//Log.v("log_tag","url: " + url);

// //In case you want to delete the file
// boolean deleted = mypath.delete();
// Log.v("log_tag","deleted: " + mypath.toString() + deleted);
// //If you want to convert the image to string use base64 converter

}
catch(Exception e)
{
Log.v("log_tag", e.toString());
}
}

public void clear()
{
path.reset();
invalidate();
}

@Override
protected void onDraw(Canvas canvas)
{
canvas.drawPath(path, paint);
}

@Override
public boolean onTouchEvent(MotionEvent event)
{
float eventX = event.getX();
float eventY = event.getY();
mGetSign.setEnabled(true);

switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
path.moveTo(eventX, eventY);
lastTouchX = eventX;
lastTouchY = eventY;
return true;

case MotionEvent.ACTION_MOVE:

case MotionEvent.ACTION_UP:

resetDirtyRect(eventX, eventY);
int historySize = event.getHistorySize();
for (int i = 0; i < historySize; i++)
{
float historicalX = event.getHistoricalX(i);
float historicalY = event.getHistoricalY(i);
expandDirtyRect(historicalX, historicalY);
path.lineTo(historicalX, historicalY);
}
path.lineTo(eventX, eventY);
break;

default:
debug("Ignored touch event: " + event.toString());
return false;
}

invalidate((int) (dirtyRect.left - HALF_STROKE_WIDTH),
(int) (dirtyRect.top - HALF_STROKE_WIDTH),
(int) (dirtyRect.right + HALF_STROKE_WIDTH),
(int) (dirtyRect.bottom + HALF_STROKE_WIDTH));

lastTouchX = eventX;
lastTouchY = eventY;

return true;
}

private void debug(String string)
{
}

private void expandDirtyRect(float historicalX, float historicalY)
{
if (historicalX < dirtyRect.left)
{
dirtyRect.left = historicalX;
}
else if (historicalX > dirtyRect.right)
{
dirtyRect.right = historicalX;
}

if (historicalY < dirtyRect.top)
{
dirtyRect.top = historicalY;
}
else if (historicalY > dirtyRect.bottom)
{
dirtyRect.bottom = historicalY;
}
}

private void resetDirtyRect(float eventX, float eventY)
{
dirtyRect.left = Math.min(lastTouchX, eventX);
dirtyRect.right = Math.max(lastTouchX, eventX);
dirtyRect.top = Math.min(lastTouchY, eventY);
dirtyRect.bottom = Math.max(lastTouchY, eventY);
}
}

如何调用这个类?

单击主 Activity 中的按钮

your_button.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent intent = new Intent(SigntuareCaptureActivity.this, Capture.class);
startActivity(intent);
finish();

}
});
于 2012-11-07T10:57:49.677 回答