问题
I am trying to figure out how to simply draw a line on an image that is being set in Picasso. I found that if I simply set the image, given a URI, with Picasso and try to draw paint to it using the following:
canvas = new Canvas(bitmap);
image.draw(canvas);
topEdge = new Paint();
topEdge.setColor(context.getResources().getColor(R.color.blue));
topEdge.setStrokeWidth(5);
canvas.drawLine(c1.getX(), c1.getY(), c2.getX(), c2.getY(), topEdge);
Then I get a crash saying that the bitmap needs to be mutable first. So I added this above that code:
Bitmap workingBitmap = ((BitmapDrawable) image.getDrawable()).getBitmap();
Bitmap mutableBitmap = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);
And then create the canvas with new Canvas(mutableBitmap)
instead. This removed the crash, however nothing is being drawn. I believe this is because my Picasso is setting the image before, so now I need to reset Picasso with this new mutable bitmap. The problem is this code is in the onSuccess() callback for Picasso. What can I do to allow Paint to be drawn on an image through Picasso?
回答1:
just follow the steps below:
Write your own class extends the class Transformation like below:
class DrawLineTransformation implements Transformation { @Override public String key() { // TODO Auto-generated method stub return "drawline"; } @Override public Bitmap transform(Bitmap bitmap) { // TODO Auto-generated method stub synchronized (DrawLineTransformation.class) { if(bitmap == null) { return null; } Bitmap resultBitmap = bitmap.copy(bitmap.getConfig(), true); Canvas canvas = new Canvas(resultBitmap); Paint paint = new Paint(); paint.setColor(Color.BLUE); paint.setStrokeWidth(10); canvas.drawLine(0, resultBitmap.getHeight()/2, resultBitmap.getWidth(), resultBitmap.getHeight()/2, paint); bitmap.recycle(); return resultBitmap; } } }
2、Add the Transformation to RequestCreator created with Picasso.load() function like below:
Picasso picasso = Picasso.with(getApplicationContext()); DrawLineTransformation myTransformation = new DrawLineTransformation(); picasso.load("http://www.baidu.com/img/bdlogo.png").transform(myTransformation).into(imageview);
That's all steps you need to do , just enjoy!
来源:https://stackoverflow.com/questions/27081534/draw-a-line-on-imageview-set-by-picasso