我们要处理一张图片,并不会直接在这张图片上直接进行处理,一般都会在内存中创建这张图片的copy,然后在这张copy上对图片进行处理
创建图片内存拷贝
根据原图创建大小一摸一样的空白图片。
Bitmap bitmapCopy = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
当然,创建的图片的副本尺寸也可以比原图不一样,
Bitmap bitmapCopy = Bitmap.createBitmap(bitmap.getWidth()*1.5, bitmap.getHeight()*1.5, bitmap.getConfig());
注:网络图片的话,可以通过Picasso来获取bitmap,一定要在子线程,耗时操作
new Thread(){ @Override public void run() { super.run(); try { bitmap_xk = Picasso.with(PreviewPicActivity.this).load(R.drawable.xk).resize(1536,768).get(); } catch (IOException e) { e.printStackTrace(); } } }.start();
根据空白图片创建一个画布
Canvas canvas = new Canvas(bitmapCopy);
创建画笔,设置画笔属性
Paint paint = new Paint(); paint.setColor(Color.parseColor("#000000")); paint.setTextSize(18); paint.setAntiAlias(true);//抗锯齿
临摹
Matrix matrix = new Matrix(); canvas.drawBitmap(bitmap(原图), matrix, paint);
至此,已经将一张图片copy到内存中
开始往照片上写字
如果文字很短,不需要换行
canvas.drawText()
当写的是多行文本时,如何控制换行—>StaticLayout
//设置画笔
TextPaint textPaint = new TextPaint();
textPaint.setColor(Color.parseColor("#ffffff"));
//确定祝福文字的大小,因为图片像素不一样,为了达到统一效果,按照图片像素来确定文字大小
float textsize = (float) (bitmap.getHeight() * 0.1);
textPaint.setTextSize(textsize);
textPaint.setAntiAlias(true);
//文字换行最大宽度,在这里我们想让当文字超过图片宽度50%时,就换行
int msgMaxWidth = (int) (bitmap.getWidth() * 0.50);
StaticLayout layout = new StaticLayout(content, textPaint, msgMaxWidth,
Layout.Alignment.ALIGN_NORMAL, 1.0F, 0.0F, true);
canvas.save();
canvas.translate(startX, startY);//从20,20开始画
layout.draw(canvas);
canvas.restore();//别忘了restore
public StaticLayout(CharSequence source, TextPaint paint,
int width, Alignment align, float spacingmult, float spacingadd,boolean includepad)
source:文本内容
textPaint:画笔
width:layout的宽度,字符串超出宽度时自动换行。
Alignment:layout的对齐方式,有ALIGN_CENTER, ALIGN_NORMAL, ALIGN_OPPOSITE 三种。
spacingmult:相对行间距,相对字体大小,1.5f表示行间距为1.5倍的字体高度。
spacingadd:在基础行距上添加多少(实际行间距等于这两者的和)。
includepad:不懂,写true先
把内存中的图片保存到本地
private void save(Bitmap bitmap_copy) {
try {
File file = new File(Environment.getExternalStorageDirectory(), "99999999999991.jpg");
FileOutputStream stream = new FileOutputStream(file);
bitmap_copy.compress(Bitmap.CompressFormat.JPEG, 100, stream);//100表示图片压缩质量,100为最高
stream.close();
Toast.makeText(PreviewPicActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(PreviewPicActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
}
}